Part Number Hot Search : 
M25V10 AD7663 CNZ111 MAX3624A RC1154 145154 C1702 8731AE
Product Description
Full Text Search
 

To Download ATTINY40-MMH Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
 Features
* High Performance, Low Power AVR(R) 8-Bit Microcontroller * Advanced RISC Architecture
- 54 Powerful Instructions - Most Single Clock Cycle Execution - 16 x 8 General Purpose Working Registers - Fully Static Operation - Up to 12 MIPS Throughput at 12 MHz Non-volatile Program and Data Memories - 4K Bytes of In-System Programmable Flash Program Memory - 256 Bytes Internal SRAM - Flash Write/Erase Cycles: 10,000 - Data Retention: 20 Years at 85oC / 100 Years at 25oC Peripheral Features - One 8-bit Timer/Counter with Two PWM Channels - One 8/16-bit Timer/Counter - 10-bit Analog to Digital Converter * 12 Single-Ended Channels - Programmable Watchdog Timer with Separate On-chip Oscillator - On-chip Analog Comparator - Master/Slave SPI Serial Interface - Slave TWI Serial Interface Special Microcontroller Features - In-System Programmable - External and Internal Interrupt Sources - Low Power Idle, ADC Noise Reduction, Stand-by and Power-down Modes - Enhanced Power-on Reset Circuit - Internal Calibrated Oscillator I/O and Packages - 20-pin SOIC/TSSOP: 18 Programmable I/O Lines - 20-pad VQFN/MLF: 18 Programmable I/O Lines Operating Voltage: - 1.8 - 5.5V Programming Voltage: - 5V Speed Grade - 0 - 4 MHz @ 1.8 - 5.5V - 0 - 8 MHz @ 2.7 - 5.5V - 0 - 12 MHz @ 4.5 - 5.5V Industrial Temperature Range Low Power Consumption - Active Mode: * 200 A at 1 MHz and 1.8V - Idle Mode: * 25 A at 1 MHz and 1.8V - Power-down Mode: * < 0.1 A at 1.8V
*
*
8-bit Microcontroller with 4K Bytes In-System Programmable Flash ATtiny40 Preliminary
*
*
* * *
* *
Rev. 8263A-AVR-08/10
1. Pin Configurations
Figure 1-1. Pinout of ATtiny40
SOIC/TSSOP
(PCINT8/ADC8) PB0 (PCINT7/ADC7) PA7 (PCINT6/ADC6) PA6 (PCINT5/ADC5/OC0B) PA5 (PCINT4/ADC4/T0) PA4 (PCINT3/ADC3) PA3 (PCINT2/ADC2/AIN1) PA2 (PCINT1/ADC1/AIN0) PA1 (PCINT0/ADC0) PA0 GND
1 2 3 4 5 6 7 8 9 10
20 19 18 17 16 15 14 13 12 11
PB1 (ADC9/PCINT9) PB2 (ADC10/PCINT10) PB3 (ADC11/PCINT11) PC0 (OC0A/SS/PCINT12) PC1 (SCK/SCL/ICP1/T1/PCINT13) PC2 (INT0/CLKO/MISO/PCINT14) PC3 (RESET/PCINT15) PC4 (MOSI/SDA/TPIDATA/PCINT16) PC5 (CLKI/TPICLK/PCINT17) VCC
MLF/VQFN
PB2 (ADC10/PCINT10) 17 PB3 (ADC11/PCINT11) 16 15 14 13 12 11 10 6 7 8 9 PB0 (ADC8/PCINT8) 19 PB1 (ADC9/PCINT9) 18 PA7 (ADC7/PCINT7) (PCINT6/ADC6) PA6 (PCINT5/ADC5/OC0B) PA5 (PCINT4/ADC4/T0) PA4 (PCINT3/ADC3) PA3 (PCINT2/ADC2/AIN1) PA2 1 2 3 4 5 20
PC0 (OC0A/SS/PCINT12) PC1 (SCK/SCL/ICP1/T1/PCINT13) PC2 (INT0/CLKO/MISO/PCINT14) PC3 (RESET/PCINT15) PC4 (MOSI/SDA/TPIDATA/PCINT16)
GND
NOTE: Bottom pad should be soldered to ground.
1.1
1.1.1
Pin Description
VCC Supply voltage.
1.1.2
GND Ground.
1.1.3
RESET Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running and provided the reset pin has not been disabled. The minimum pulse length is given in Table 21-4 on page 168. Shorter pulses are not guaranteed to generate a reset. The reset pin can also be used as a (weak) I/O pin.
2
ATtiny40
8263A-AVR-08/10
(PCINT17/CLKI/TPICLK) PC5
(PCINT1/ADC1/AIN0) PA1
(PCINT0/ADC0) PA0
VCC
ATtiny40
1.1.4 Port A (PA7:PA0) Port A is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port A output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port A pins that are externally pulled low will source current if the pull-up resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port A has alternate functions as analog inputs for the ADC, analog comparator and pin change interrupt as described in "Alternate Port Functions" on page 52. 1.1.5 Port B (PB3:PB0) Port B is a 4-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port B output buffers have symmetrical drive characteristics with both high sink and source capability. As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. The port also serves the functions of various special features of the ATtiny40, as listed on page 41. 1.1.6 Port C (PC5:PC0) Port C is a 6-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). The Port C output buffers have symmetrical drive characteristics with both high sink and source capability except PC3 which has the RESET capability. To use pin PC3 as an I/O pin, instead of RESET pin, program (`0') RSTDISBL fuse. As inputs, Port C pins that are externally pulled low will source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port C has alternate functions as analog inputs for the ADC, analog comparator and pin change interrupt as described in "Alternate Port Functions" on page 52. The port also serves the functions of various special features of the ATtiny40, as listed on page 41.
3
8263A-AVR-08/10
2. Overview
ATtiny40 is a low-power CMOS 8-bit microcontroller based on the compact AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the ATtiny40 achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. Figure 2-1. Block Diagram
VCC RESET
PROGRAMMING LOGIC
PROGRAM COUNTER
INTERNAL OSCILLATOR
CALIBRATED OSCILLATOR
PROGRAM FLASH
STACK POINTER
WATCHDOG TIMER
TIMING AND CONTROL
INSTRUCTION REGISTER
SRAM
RESET FLAG REGISTER
INSTRUCTION DECODER
INTERRUPT UNIT
MCU STATUS REGISTER
CONTROL LINES
GENERAL PURPOSE REGISTERS
X Y Z
TIMER/ COUNTER0
TIMER/ COUNTER1
ALU
SPI
ANALOG COMPARATOR
ISP INTERFACE
STATUS REGISTER
TWI
ADC
8-BIT DATA BUS
DATA REGISTER PORT A
DIRECTION REG. PORT A
DATA REGISTER PORT B
DIRECTION REG. PORT B
DATA REGISTER PORT C
DIRECTION REG. PORT C
DRIVERS PORT A
DRIVERS PORT B
DRIVERS PORT C
PA[7:0]
PB[3:0]
PC[5:0]
GND
The AVR core combines a rich instruction set with 16 general purpose working registers and system registers. All registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle.
4
ATtiny40
8263A-AVR-08/10
ATtiny40
The resulting architecture is compact and code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers. The ATtiny40 provides the following features: 4K bytes of In-System Programmable Flash, 256 bytes of SRAM, twelve general purpose I/O lines, 16 general purpose working registers, an 8-bit Timer/Counter with two PWM channels, a 8/16-bit Timer/Counter, Internal and External Interrupts, an eight-channel, 10-bit ADC, a programmable Watchdog Timer with internal oscillator, a slave two-wire interface, a master/slave serial peripheral interface, an internal calibrated oscillator, and four software selectable power saving modes. Idle mode stops the CPU while allowing the SRAM, Timer/Counter, ADC, Analog Comparator, and interrupt system to continue functioning. ADC Noise Reduction mode minimizes switching noise during ADC conversions by stopping the CPU and all I/O modules except the ADC. In Power-down mode registers keep their contents and all chip functions are disabled until the next interrupt or hardware reset. In Standby mode, the oscillator is running while the rest of the device is sleeping, allowing very fast start-up combined with low power consumption. The device is manufactured using Atmel's high density non-volatile memory technology. The onchip, in-system programmable Flash allows program memory to be re-programmed in-system by a conventional, non-volatile memory programmer. The ATtiny40 AVR is supported by a suite of program and system development tools, including macro assemblers and evaluation kits.
5
8263A-AVR-08/10
3. General Information
3.1 Resources
A comprehensive set of drivers, application notes, data sheets and descriptions on development tools are available for download at http://www.atmel.com/avr.
3.2
Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details.
3.3
Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85C or 100 years at 25C.
3.4
Disclaimer
Typical values contained in this datasheet are based on simulations and characterization of other AVR microcontrollers manufactured on the same process technology. Min and Max values will be available after the device has been characterized.
6
ATtiny40
8263A-AVR-08/10
ATtiny40
4. CPU Core
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts.
4.1
Architectural Overview
Figure 4-1. Block Diagram of the AVR Architecture
Data Bus 8-bit
Flash Program Memory
Program Counter
Status and Control
Interrupt Unit Watchdog Timer Analog Comparator
Instruction Register
16 x 8 General Purpose Registrers
Indirect Addressing
Instruction Decoder
ADC ALU Timer/Counter 0
Control Lines
Direct Addressing
Timer/Counter 1
Data SRAM
SPI
TWI Slave I/O Lines
In order to maximize performance and parallelism, the AVR uses a Harvard architecture - with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is In-System Reprogrammable Flash memory. The fast-access Register File contains 16 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typical ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File - in one clock cycle. 7
8263A-AVR-08/10
Six of the 16 registers can be used as three 16-bit indirect address register pointers for data space addressing - enabling efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in Flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation. Program flow is provided by conditional and unconditional jump and call instructions, capable of directly addressing the whole address space. Most AVR instructions have a single 16-bit word format but 32-bit wide instructions also exist. The actual instruction set varies, as some devices only implement a part of the instruction set. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through the four different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O memory can be accessed as the data space locations, 0x0000 - 0x003F.
4.2
ALU - Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 16 general purpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories - arithmetic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for a detailed description.
4.3
Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in document "AVR Instruction Set" and section "Instruction Set Summary" on page 203. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software.
8
ATtiny40
8263A-AVR-08/10
ATtiny40
4.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: * One 8-bit output operand and one 8-bit result input * Two 8-bit output operands and one 8-bit result input * One 16-bit output operand and one 16-bit result input Figure 4-2 below shows the structure of the 16 general purpose working registers in the CPU. Figure 4-2. AVR CPU General Purpose Working Registers
7 R16 R17 General Purpose Working Registers R18 ... R26 R27 R28 R29 R30 R31 X-register Low Byte X-register High Byte Y-register Low Byte Y-register High Byte Z-register Low Byte Z-register High Byte 0
Note:
A typical implementation of the AVR register file includes 32 general prupose registers but ATtiny40 implements only 16 registers. For reasons of compatibility the registers are numbered R16...R31 and not R0...R15.
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions. 4.4.1 The X-register, Y-register, and Z-register Registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described in Figure 4-3.
9
8263A-AVR-08/10
Figure 4-3.
The X-, Y-, and Z-registers
15 XH 0 R27 7 R26 XL 0 0
X-register
7
15 Y-register 7
YH 0 R29 7
YL
0 0
R28
15 Z-register 7
ZH 0 R31 7
ZL
0 0
R30
In different addressing modes these address registers function as automatic increment and automatic decrement (see document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for details).
4.5
Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer. The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above 0x40. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the Stack with return from subroutine RET or return from interrupt RETI. The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register will not be present.
4.6
Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used.
10
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 4-4. The Parallel Instruction Fetches and Instruction Executions
T1 T2 T3 T4
clkCPU 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch
Figure 4-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. Figure 4-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using two register operands is executed, and the result is stored back to the destination register. Figure 4-5. Single Cycle ALU Operation
T1 T2 T3 T4
clkCPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back
4.7
Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate Program Vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in "Interrupts" on page 40. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 - the External Interrupt Request 0. When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled
11
8263A-AVR-08/10
interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction - RETI - is executed. There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in the following example. Assembly Code Example
sei sleep ; set Global Interrupt Enable ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending interrupt(s) Note: See "Code Examples" on page 6.
4.7.1
Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the Program Vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode. A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.
12
ATtiny40
8263A-AVR-08/10
ATtiny40
4.8
4.8.1
Register Description
CCP - Configuration Change Protection Register
Bit 0x3C Read/Write Initial Value W 0 W 0 W 0 W 0 7 6 5 4 CCP[7:0] W 0 W 0 W 0 W 0 3 2 1 0 CCP
* Bits 7:0 - CCP[7:0]: Configuration Change Protection In order to change the contents of a protected I/O register the CCP register must first be written with the correct signature. After CCP is written the protected I/O registers may be written to during the next four CPU instruction cycles. All interrupts are ignored during these cycles. After these cycles interrupts are automatically handled again by the CPU, and any pending interrupts will be executed according to their priority. When the protected I/O register signature is written, CCP0 will read as one as long as the protected feature is enabled, while CCP[7:1] will always read as zero. Table 4-1 shows the signatures that are in recognised. Table 4-1.
Signature 0xD8 Notes:
Signatures Recognised by the Configuration Change Protection Register
Group IOREG: CLKMSR, CLKPSR, WDTCSR , MCUCR
(1) (2)
Description Protected I/O register
1. Only WDE and WDP[3:0] bits are protected in WDTCSR. 2. Only BODS bit is protected in MCUCR.
4.8.2
SPH and SPL - Stack Pointer Register
Bit 0x3E 0x3D Read/Write Read/Write Initial Value Initial Value 15 SP15 SP7 7 R R/W
RAMEND RAMEND
14 SP14 SP6 6 R R/W
RAMEND RAMEND
13 SP13 SP5 5 R R/W
RAMEND RAMEND
12 SP12 SP4 4 R R/W
RAMEND RAMEND
11 SP11 SP3 3 R R/W
RAMEND RAMEND
10 SP10 SP2 2 R R/W
RAMEND RAMEND
9 SP9 SP1 1 R R/W
RAMEND RAMEND
8 SP8 SP0 0 R R/W
RAMEND RAMEND
SPH SPL
* Bits 15:0 - SP[15:0]: Stack Pointer The Stack Pointer register points to the top of the stack, which is implemented as growing from higher memory locations to lower memory locations. Hence, a stack PUSH command decreases the Stack Pointer. The stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer in ATtiny40 is implemented as two 8-bit registers in the I/O space.
13
8263A-AVR-08/10
4.8.3
SREG - Status Register
Bit 0x3F Read/Write Initial Value 7 I R/W 0 6 T R/W 0 5 H R/W 0 4 S R/W 0 3 V R/W 0 2 N R/W 0 1 Z R/W 0 0 C R/W 0 SREG
* Bit 7 - I: Global Interrupt Enable The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, as described in the document "AVR Instruction Set" and "Instruction Set Summary" on page 203. * Bit 6 - T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. * Bit 5 - H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry is useful in BCD arithmetic. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information. * Bit 4 - S: Sign Bit, S = N V The S-bit is always an exclusive or between the Negative Flag N and the Two's Complement Overflow Flag V. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information. * Bit 3 - V: Two's Complement Overflow Flag The Two's Complement Overflow Flag V supports two's complement arithmetics. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information. * Bit 2 - N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information. * Bit 1 - Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information. * Bit 0 - C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for detailed information.
14
ATtiny40
8263A-AVR-08/10
ATtiny40
5. Memories
This section describes the different memories in the ATtiny40. The device has two main memory areas, the program memory space and the data memory space.
5.1
In-System Re-programmable Flash Program Memory
The ATtiny40 contains 4K byte on-chip, in-system reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 2048 x 16. The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATtiny40 Program Counter (PC) is 11 bits wide, thus capable of addressing the 2048 program memory locations, starting at 0x000. "Memory Programming" on page 156 contains a detailed description on Flash data serial downloading. Constant tables can be allocated within the entire address space of program memory. Since program memory can not be accessed directly, it has been mapped to the data memory. The mapped program memory begins at byte address 0x4000 in data memory (see Figure 5-1 on page 16). Although programs are executed starting from address 0x000 in program memory it must be addressed starting from 0x4000 when accessed via the data memory. Internal write operations to Flash program memory have been disabled and program memory therefore appears to firmware as read-only. Flash memory can still be written to externally but internal write operations to the program memory area will not be succesful. Timing diagrams of instruction fetch and execution are presented in "Instruction Execution Timing" on page 10.
5.2
Data Memory
Data memory locations include the I/O memory, the internal SRAM memory, the non-volatile memory lock bits, and the Flash memory. See Figure 5-1 on page 16 for an illustration on how the ATtiny40 memory space is organized. The first 64 locations are reserved for I/O memory, while the following 256 data memory locations (from 0x0040 to 0x013F) address the internal data SRAM. The non-volatile memory lock bits and all the Flash memory sections are mapped to the data memory space. These locations appear as read-only for device firmware. The four different addressing modes for data memory are direct, indirect, indirect with pre-decrement, and indirect with post-increment. In the register file, registers R26 to R31 function as pointer registers for indirect addressing. The IN and OUT instructions can access all 64 locations of I/O memory. Direct addressing using the LDS and STS instructions reaches the lowest 128 locations between 0x0040 and 0x00BF. The indirect addressing reaches the entire data memory space. When using indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented.
15
8263A-AVR-08/10
Figure 5-1.
Data Memory Map (Byte Addressing)
I/O SPACE SRAM DATA MEMORY (reserved) NVM LOCK BITS (reserved) CONFIGURATION BITS (reserved) CALIBRATION BITS (reserved) DEVICE ID BITS (reserved) FLASH PROGRAM MEMORY (reserved)
5.2.1
0x0000 ... 0x003F 0x0040 ... 0x013F 0x0140 ... 0x3EFF 0x3F00 ... 0x3F01 0x3F02 ... 0x3F3F 0x3F40 ... 0x3F41 0x3F42 ... 0x3F7F 0x3F80 ... 0x3F81 0x3F82 ... 0x3FBF 0x3FC0 ... 0x3FC3 0x3FC4 ... 0x3FFF 0x4000 ... 0x47FF 0x4800 ... 0xFFFF
Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 5-2. Figure 5-2. On-chip Data SRAM Access Cycles
T1 T2 T3
clkCPU Address Data WR Data RD
Compute Address Address valid
Memory Access Instruction
Next Instruction
16
ATtiny40
8263A-AVR-08/10
Read
Write
ATtiny40
5.2.2 Internal SRAM The internal SRAM is mapped in the Data Memory space starting at address 0x0040. SRAM is accessed from the CPU by using direct addressing, indirect addressing or via the RAM interface. The registers R26 to R31 function as pointer register for indirect addressing. The pointer predecrement and post-increment functions are also supported in connection with the indirect addressing. Direct addressing using the LDS and STS instructions reaches only the lowest 128 locations between 0x0040 and 0x00BF. The locations beyond the first 128 bytes between 0x00C0 and 0x013F must be accessed using either indirect addressing mode (LD and ST instructions) or via the RAM interface. The user must pay particular attention to the RAM addressing when using the RAM interface. The direct and indirect addressing modes use virtual RAM address, but the RAM interface uses physical RAM address. The virtual RAM address space mapping to physical addresses is described in Table 5-1. For example, if the data is written to RAM using the virtual RAM address 0x0100 (instruction STS or ST), it is mapped to physical RAM address 0x0000. Thus the physical RAM address 0x0000 must be written to the RAMAR register when the same data location is read back via the RAM interface. On the other hand, if the same data location is read back using direct or indirect addressing mode (instruction LDS or LD), the same virtual RAM address 0x0100 is used. Table 5-1. SRAM Address Space
Physical RAM Address 0x0040 - - - 0x00FF 0x0000 - - - 0x003F
Virtual RAM Address 0x0040 - - - 0x00FF 0x0100 - - - 0x013F
5.2.3
RAM Interface The RAM Interface consists of two registers, RAM Address Register (RAMAR) and RAM Data Register (RAMDR). The registers are accessible in I/O space. To write a location the user must first write the RAM address into RAMAR and then the data into RAMDR. Writing the data into RAMDR triggers the write operation and the data from the source register is written to RAM in address given by RAMAR within the same instruction cycle. To read a location the user must first write the RAM address into RAMAR and then read the data from RAMDR. Reading the data from RAMDR triggers the read operation and the data from
17
8263A-AVR-08/10
RAM address given by RAMAR is fetched and written to the destination register within the same instruction cycle. Assembly Code Example
RAM_write: ; Set up address (r17) in address register out RAMAR, r17 ; Write data (r16) to data register out RAMDR, r16 ret RAM_read: ; Set up address (r17) in address register out RAMAR, r17 ; Read data (r16) from data register in ret r16, RAMDR
C Code Example
void RAM_write(unsigned char ucAddress, unsigned char ucData) { /* Set up address register */ RAMAR = ucAddress; /* Write data into RAMDR */ RAMDR = ucData; } void RAM_read(unsigned char ucAddress, unsigned char ucData) { /* Set up address register */ RAMAR = ucAddress; /* Read data from RAMDR */ ucData = RAMDR; }
5.3
I/O Memory
The I/O space definition of the ATtiny40 is shown in "Register Summary" on page 201. All ATtiny40 I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed using the LD and ST instructions, enabling data transfer between the 16 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. See document "AVR Instruction Set" and section "Instruction Set Summary" on page 203 for more details. When using the I/O specific commands IN and OUT, the I/O addresses 0x00 - 0x3F must be used.
18
ATtiny40
8263A-AVR-08/10
ATtiny40
For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. Some of the status flags are cleared by writing a logical one to them. Note that CBI and SBI instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. The CBI and SBI instructions work on registers in the address range 0x00 to 0x1F, only. The I/O and Peripherals Control Registers are explained in later sections.
5.4
5.4.1
Register Description
RAMAR - RAM Address Register
Bit 0x20 Read/Write Initial Value 7 RAMAR7 R/W X 6 RAMAR6 R/W X 5 RAMAR5 R/W X 4 RAMAR4 R/W X 3 RAMAR3 R/W X 2 RAMAR2 R/W X 1 RAMAR1 R/W X 0 RAMAR0 R/W X RAMAR
* Bits 7:0 - RAMAR[7:0]: RAM Address The RAMAR register contains the RAM address bits. The RAM data bytes are addressed linearly in the range 0..255. The initial value of RAMAR is undefined and a proper value must be therefore written before the RAM may be accessed. 5.4.2 RAMDR - RAM Data Register
Bit 0x1F Read/Write Initial Value 7 RAMDR7 R/W X 6 RAMDR6 R/W X 5 RAMDR5 R/W X 4 RAMDR4 R/W X 3 RAMDR3 R/W X 2 RAMDR2 R/W X 1 RAMDR1 R/W X 0 RAMDR0 R/W X RAMDR
* Bits 7:0 - RAMDR[7:0]: RAM Data For the RAM write operation, the RAMDR register contains the RAM data to be written to the RAM in address given by the RAMAR register. For the RAM read operation, the RAMDR contains the data read out from the RAM at the address given by RAMAR.
19
8263A-AVR-08/10
6. Clock System
Figure 6-1 presents the principal clock systems and their distribution in ATtiny40. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes and power reduction register bits, as described in "Power Management and Sleep Modes" on page 27. The clock systems is detailed below. Figure 6-1. Clock Distribution
ANALOG-TO-DIGITAL CONVERTER clk ADC GENERAL I/O MODULES clk I/O CPU CORE RAM NVM
clk CPU
clk NVM
CLOCK CONTROL UNIT
SOURCE CLOCK
RESET LOGIC
WATCHDOG CLOCK
CLOCK PRESCALER
WATCHDOG TIMER
CLOCK SWITCH
EXTERNAL CLOCK
WATCHDOG OSCILLATOR
CALIBRATED OSCILLATOR
6.1
6.1.1
Clock Subsystems
The clock subsystems are detailed in the sections below. CPU Clock - clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVR Core. Examples of such modules are the General Purpose Register File, the System Registers and the SRAM data memory. Halting the CPU clock inhibits the core from performing general operations and calculations. I/O Clock - clkI/O The I/O clock is used by the majority of the I/O modules, like Timer/Counter. The I/O clock is also used by the External Interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the I/O clock is halted. NVM clock - clkNVM The NVM clock controls operation of the Non-Volatile Memory Controller. The NVM clock is usually active simultaneously with the CPU clock.
6.1.2
6.1.3
20
ATtiny40
8263A-AVR-08/10
ATtiny40
6.1.4 ADC Clock - clkADC The ADC is provided with a dedicated clock domain. This allows halting the CPU and I/O clocks in order to reduce noise generated by digital circuitry. This gives more accurate ADC conversion results.
6.2
Clock Sources
All synchronous clock signals are derived from the main clock. The device has three alternative sources for the main clock, as follows: * Calibrated Internal 8 MHz Oscillator (see page 21) * External Clock (see page 21) * Internal 128 kHz Oscillator (see page 22) See Table 6-3 on page 24 on how to select and change the active clock source.
6.2.1
Calibrated Internal 8 MHz Oscillator The calibrated internal oscillator provides an approximately 8 MHz clock signal. Though voltage and temperature dependent, this clock can be very accurately calibrated by the user. See Table 21-2 on page 167, and "Internal Oscillator Speed" on page 198 for more details. This clock may be selected as the main clock by setting the Clock Main Select bits CLKMS[1:0] in CLKMSR to 0b00. Once enabled, the oscillator will operate with no external components. During reset, hardware loads the calibration byte into the OSCCAL register and thereby automatically calibrates the oscillator. The accuracy of this calibration is shown as Factory calibration in Table 21-2 on page 167. When this oscillator is used as the main clock, the watchdog oscillator will still be used for the watchdog timer and reset time-out. For more information on the pre-programmed calibration value, see section "Calibration Section" on page 159.
6.2.2
External Clock To use the device with an external clock source, CLKI should be driven as shown in Figure 6-2. The external clock is selected as the main clock by setting CLKMS[1:0] bits in CLKMSR to 0b10. Figure 6-2. External Clock Drive Configuration
EXTERNAL CLOCK SIGNAL
CLKI
GND
When applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the MCU. A variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. It is required to ensure that the MCU is kept in reset during such changes in the clock frequency.
21
8263A-AVR-08/10
6.2.3
Internal 128 kHz Oscillator The internal 128 kHz oscillator is a low power oscillator providing a clock of 128 kHz. The frequency depends on supply voltage, temperature and batch variations. This clock may be select as the main clock by setting the CLKMS[1:0] bits in CLKMSR to 0b01. Switching Clock Source The main clock source can be switched at run-time using the "CLKMSR - Clock Main Settings Register" on page 24. When switching between any clock sources, the clock system ensures that no glitch occurs in the main clock. Default Clock Source The calibrated internal 8 MHz oscillator is always selected as main clock when the device is powered up or has been reset. The synchronous system clock is the main clock divided by 8, controlled by the System Clock Prescaler. The Clock Prescaler Select Bits can be written later to change the system clock frequency. See "System Clock Prescaler".
6.2.4
6.2.5
6.3
System Clock Prescaler
The system clock is derived from the main clock via the System Clock Prescaler. The system clock can be divided by setting the "CLKPSR - Clock Prescale Register" on page 24. The system clock prescaler can be used to decrease power consumption at times when requirements for processing power is low or to bring the system clock within limits of maximum frequency. The prescaler can be used with all main clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. The System Clock Prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation.
6.3.1
Switching Prescaler Setting When switching between prescaler settings, the system clock prescaler ensures that no glitch occurs in the system clock and that no intermediate frequency is higher than neither the clock frequency corresponding the previous setting, nor the clock frequency corresponding to the new setting. The ripple counter that implements the prescaler runs at the frequency of the main clock, which may be faster than the CPU's clock frequency. Hence, it is not possible to determine the state of the prescaler - even if it were readable, and the exact time it takes to switch from one clock division to another cannot be exactly predicted. From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2*T2 before the new clock frequency is active. In this interval, two active clock edges are produced. Here, T1 is the previous clock period, and T2 is the period corresponding to the new prescaler setting.
6.4
6.4.1
Starting
Starting from Reset The internal reset is immediately asserted when a reset source goes active. The internal reset is kept asserted until the reset source is released and the start-up sequence is completed. The start-up sequence includes three steps, as follows. 1. The first step after the reset source has been released consists of the device counting the reset start-up time. The purpose of this reset start-up time is to ensure that supply
22
ATtiny40
8263A-AVR-08/10
ATtiny40
voltage has reached sufficient levels. The reset start-up time is counted using the internal 128 kHz oscillator. See Table 6-1 for details of reset start-up time. Note that the actual supply voltage is not monitored by the start-up logic. The device will count until the reset start-up time has elapsed even if the device has reached sufficient supply voltage levels earlier. 2. The second step is to count the oscillator start-up time, which ensures that the calibrated internal oscillator has reached a stable state before it is used by the other parts of the system. The calibrated internal oscillator needs to oscillate for a minimum number of cycles before it can be considered stable. See Table 6-1 for details of the oscillator start-up time. 3. The last step before releasing the internal reset is to load the calibration and the configuration values from the Non-Volatile Memory to configure the device properly. The configuration time is listed in Table 6-1. Table 6-1.
Reset 64 ms Notes:
Start-up Times when Using the Internal Calibrated Oscillator
Oscillator 6 cycles Configuration 21 cycles Total start-up time 64 ms + 6 oscillator cycles + 21 system clock cycles (1)(2)
1. After powering up the device or after a reset the system clock is automatically set to calibrated internal 8 MHz oscillator, divided by 8 2. When the Brown-out Detection is enabled, the reset start-up time is 128 ms after powering up the device.
6.4.2
Starting from Power-Down Mode When waking up from Power-down sleep mode, the supply voltage is assumed to be at a sufficient level and only the oscillator start-up time is counted to ensure the stable operation of the oscillator. The oscillator start-up time is counted on the selected main clock, and the start-up time depends on the clock selected. See Table 6-2 for details. Table 6-2. Start-up Time from Power-Down Sleep Mode.
Oscillator start-up time 6 cycles Notes: Total start-up time 6 oscillator cycles (1)(2)
1. The start-up time is measured in main clock oscillator cycles. 2. When using software BOD disable, the wake-up time from sleep mode will be approximately 60s.
6.4.3
Starting from Idle / ADC Noise Reduction / Standby Mode When waking up from Idle, ADC Noise Reduction or Standby Mode, the oscillator is already running and no oscillator start-up time is introduced.
23
8263A-AVR-08/10
6.5
6.5.1
Register Description
CLKMSR - Clock Main Settings Register
Bit 0x37 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 CLKMS1 R/W 0 0 CLKMS0 R/W 0 CLKMSR
* Bits 7:2 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 1:0 - CLKMS[1:0]: Clock Main Select Bits These bits select the main clock source of the system. The bits can be written at run-time to switch the source of the main clock. The clock system ensures glitch free switching of the main clock source. The main clock alternatives are shown in Table 6-3. Table 6-3.
CLKM1 0 0 1 1
Selection of Main Clock
CLKM0 0 1 0 1 Main Clock Source Calibrated Internal 8 MHzOscillator Internal 128 kHz Oscillator (WDT Oscillator) External clock Reserved
To avoid unintentional switching of main clock source, a protected change sequence must be followed to change the CLKMS bits, as follows: 1. Write the signature for change enable of protected I/O register to register CCP 2. Within four instruction cycles, write the CLKMS bits with the desired value
6.5.2
CLKPSR - Clock Prescale Register
Bit 0x36 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 CLKPS3 R/W 0 2 CLKPS2 R/W 0 1 CLKPS1 R/W 1 0 CLKPS0 R/W 1 CLKPSR
* Bits 7:4 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 3:0 - CLKPS[3:0]: Clock Prescaler Select Bits 3 - 0 These bits define the division factor between the selected clock source and the internal system clock. These bits can be written at run-time to vary the clock frequency and suit the application
24
ATtiny40
8263A-AVR-08/10
ATtiny40
requirements. As the prescaler divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced accordingly. The division factors are given in Table 6-4. Table 6-4.
CLKPS3 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
Clock Prescaler Select
CLKPS2 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 CLKPS1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 CLKPS0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Clock Division Factor 1 2 4 8 (default) 16 32 64 128 256 Reserved Reserved Reserved Reserved Reserved Reserved Reserved
To avoid unintentional changes of clock frequency, a protected change sequence must be followed to change the CLKPS bits: 1. Write the signature for change enable of protected I/O register to register CCP 2. Within four instruction cycles, write the desired value to CLKPS bits At start-up, the CLKPS bits will be reset to 0b0011 to select the clock division factor of 8. The application software must ensure that a sufficient division factor is chosen if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. 6.5.3 OSCCAL - Oscillator Calibration Register
.
Bit 0x39 Read/Write Initial Value
7 CAL7 R/W 0
6 CAL6 R/W 0
5 CAL5 R/W 0
4 CAL4 R/W 0
3 CAL3 R/W 0
2 CAL2 R/W 0
1 CAL1 R/W 0
0 CAL0 R/W 0 OSCCAL
* Bits 7:0 - CAL[7:0]: Oscillator Calibration Value The oscillator calibration register is used to trim the calibrated internal oscillator and remove process variations from the oscillator frequency. A pre-programmed calibration value is automatically written to this register during chip reset, giving the factory calibrated frequency as specified in Table 21-2, "Calibration Accuracy of Internal RC Oscillator," on page 167.
25
8263A-AVR-08/10
The application software can write this register to change the oscillator frequency. The oscillator can be calibrated to frequencies as specified in Table 21-2, "Calibration Accuracy of Internal RC Oscillator," on page 167. Calibration outside the range given is not guaranteed. The CAL[7:0] bits are used to tune the frequency of the oscillator. A setting of 0x00 gives the lowest frequency, and a setting of 0xFF gives the highest frequency.
26
ATtiny40
8263A-AVR-08/10
ATtiny40
7. Power Management and Sleep Modes
The high performance and industry leading code efficiency makes the AVR microcontrollers an ideal choise for low power applications. In addition, sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application's requirements.
7.1
Sleep Modes
Figure 6-1 on page 20 presents the different clock systems and their distribution in ATtiny40. The figure is helpful in selecting an appropriate sleep mode. Table 7-1 shows the different sleep modes and their wake up sources. Table 7-1. Active Clock Domains and Wake-up Sources in Different Sleep Modes.
Active Clock Domains Oscillators Main Clock Source Enabled INT0 and Pin Change Wake-up Sources
TWI Slave
Watchdog Interrupt
Sleep Mode Idle ADC Noise Reduction Standby Power-down Notes:
X
X X
X X X
X X(1) X X
(1) (1)
X X X X
X X(2) X
(2)
X X
X(2)
1. For INT0, only level interrupt. 2. Only TWI address match interrupt.
To enter any of the four sleep modes, the SE bits in MCUCR must be written to logic one and a SLEEP instruction must be executed. The SM[2:0] bits in the MCUCR register select which sleep mode (Idle, ADC Noise Reduction, Standby or Power-down) will be activated by the SLEEP instruction. See Table 7-2 for a summary. If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector. Note that if a level triggered interrupt is used for wake-up the changed level must be held for some time to wake up the MCU (and for the MCU to enter the interrupt service routine). See "External Interrupts" on page 41 for details. 7.1.1 Idle Mode When bits SM[2:0] are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing the analog comparator, timer/counters, watchdog, TWI, SPI and the interrupt system to continue operating. This sleep mode basically halts clkCPU and clkNVM, while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the timer overflow. If wake-up from the analog comparator interrupt is not required, the 27
8263A-AVR-08/10
Other I/O X
clkNVM
clkCPU
clkADC
ADC
clkIO
analog comparator can be powered down by setting the ACD bit in "ACSRA - Analog Comparator Control and Status Register" on page 102. This will reduce power consumption in idle mode. If the ADC is enabled, a conversion starts automatically when this mode is entered. 7.1.2 ADC Noise Reduction Mode When bits SM[2:0] are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the CPU but allowing the ADC, the external interrupts, TWI and the watchdog to continue operating (if enabled). This sleep mode halts clkI/O, clkCPU, and clkNVM, while allowing the other clocks to run. This mode improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is enabled, a conversion starts automatically when this mode is entered. 7.1.3 Power-down Mode When bits SM[2:0] are written to 010, the SLEEP instruction makes the MCU enter Power-down mode. In this mode, the oscillator is stopped, while the external interrupts, TWI and the watchdog continue operating (if enabled). Only a watchdog reset, an external level interrupt on INT0, a pin change interrupt, or a TWI slave interrupt can wake up the MCU. This sleep mode halts all generated clocks, allowing operation of asynchronous modules only. Standby Mode When bits SM[2:0] are written to 100, the SLEEP instruction makes the MCU enter Standby mode. This mode is identical to Power-down with the exception that the oscillator is kept running. This reduces wake-up time, because the oscillator is already running and doesn't need to be started up.
7.1.4
7.2
Software BOD Disable
When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses (see Table 20-5 on page 158), the BOD is actively monitoring the supply voltage during a sleep period. In some devices it is possible to save power by disabling the BOD by software in Power-down and Stand-by sleep modes. The sleep mode power consumption will then be at the same level as when BOD is globally disabled by fuses. If BOD is disabled by software, the BOD function is turned off immediately after entering the sleep mode. Upon wake-up from sleep, BOD is automatically enabled again. This ensures safe operation in case the VCC level has dropped during the sleep period. When the BOD has been disabled, the wake-up time from sleep mode will be approximately 60 s to ensure that the BOD is working correctly before the MCU continues executing code. BOD disable is controlled by the BODS (BOD Sleep) bit of MCU Control Register, see "MCUCR - MCU Control Register" on page 30. Writing this bit to one turns off BOD in Power-down and Stand-by, while writing a zero keeps the BOD active. The default setting is zero, i.e. BOD active. Writing to the BODS bit is controlled by a timed sequence, see "MCUCR - MCU Control Register" on page 30.
7.3
Power Reduction Register
The Power Reduction Register (PRR), see "PRR - Power Reduction Register" on page 31, provides a method to reduce power consumption by stopping the clock to individual peripherals. When the clock for a peripheral is stopped then:
28
ATtiny40
8263A-AVR-08/10
ATtiny40
* The current state of the peripheral is frozen. * The associated registers can not be read or written. * Resources used by the peripheral will remain occupied. The peripheral should in most cases be disabled before stopping the clock. Clearing the PRR bit wakes up the peripheral and puts it in the same state as before shutdown. Peripheral shutdown can be used in Idle mode and Active mode to significantly reduce the overall power consumption. See "Supply Current of I/O Modules" on page 171 for examples. In all other sleep modes, the clock is already stopped.
7.4
Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR Core controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the device's functions are operating. All functions not needed should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption.
7.4.1
Analog Comparator When entering Idle mode, the analog comparator should be disabled if not used. In the powerdown mode, the analog comparator is automatically disabled. See "Analog Comparator" on page 101 for further details. Analog to Digital Converter If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be disabled before entering any sleep mode. When the ADC is turned off and on again, the next conversion will be an extended conversion. See "Analog to Digital Converter" on page 105 for details on ADC operation. Watchdog Timer If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute significantly to the total current consumption. Refer to "Watchdog Timer" on page 35 for details on how to configure the Watchdog Timer. Brown-out Detector If the Brown-out Detector is not needed in the application, this module should be turned off. If the Brown-out Detector is enabled by the BODLEVEL Fuses, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this will contribute significantly to the total current consumption. See "Brown-out Detection" on page 34 and "Software BOD Disable" on page 28 for details on how to configure the Brown-out Detector. Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing is then to ensure that no pins drive resistive loads. In sleep modes where the I/O clock (clkI/O) is stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. Refer to the section "Digital Input Enable and Sleep Modes" on page 50 for details on which pins are enabled. If the input 29
7.4.2
7.4.3
7.4.4
7.4.5
8263A-AVR-08/10
buffer is enabled and the input signal is left floating or has an analog signal level close to VCC/2, the input buffer will use excessive power. For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VCC/2 on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to the Digital Input Disable Register (DIDR0). Refer to "DIDR0 - Digital Input Disable Register 0" on page 104 for details.
7.5
7.5.1
Register Description
MCUCR - MCU Control Register The MCU Control Register contains bits for controlling external interrupt sensing and power management.
Bit 0x3A Read/Write Initial Value 7 ISC01 R/W 0 6 ISC00 R/W 0 5 - R 0 4 BODS R/W 0 3 SM2 R/W 0 2 SM1 R/W 0 1 SM0 R/W 0 0 SE R/W 0 MCUCR
* Bit 5 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 4 - BODS: BOD Sleep In order to disable BOD during sleep (see Table 7-1 on page 27) the BODS bit must be written to logic one. This is controlled by a protected change sequence, as follows: 1. Write the signature for change enable of protected I/O registers to register CCP. 2. Within four instruction cycles write the BODS bit. A sleep instruction must be executed while BODS is active in order to turn off the BOD for the actual sleep mode. The BODS bit is automatically cleared when the device wakes up. Alternatively the BODS bit can be cleared by writing logic zero to it. This does not require protected sequence. * Bits 3:1 - SM[2:0]: Sleep Mode Select Bits 2, 1 and 0 These bits select between available sleep modes, as shown in Table 7-2. Table 7-2.
SM2 0 0 0 0 1 1 1 1
Sleep Mode Select
SM1 0 0 1 1 0 0 1 1 SM0 0 1 0 1 0 1 0 1 Sleep Mode Idle ADC noise reduction Power-down Reserved Standby Reserved Reserved Reserved
30
ATtiny40
8263A-AVR-08/10
ATtiny40
* Bit 0 - SE: Sleep Enable The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer's purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up. 7.5.2 PRR - Power Reduction Register
Bit 0x35 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 PRTWI R/W 0 3 PRSPI R/W 0 2 PRTIM1 R/W 0 1 PRTIM0 R/W 0 0 PRADC R/W 0 PRR
* Bits 7:5 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 4 - PRTWI: Power Reduction Two-Wire Interface Writing a logic one to this bit shuts down the Two-Wire Interface module. * Bit 3 - PRSPI: Power Reduction Serial Peripheral Interface Writing a logic one to this bit shuts down the Serial Peripheral Interface module. * Bit 2 - PRTIM1: Power Reduction Timer/Counter1 Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1 is enabled, operation will continue like before the shutdown. * Bit 1 - PRTIM0: Power Reduction Timer/Counter0 Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation will continue like before the shutdown. * Bit 0 - PRADC: Power Reduction ADC Writing a logic one to this bit shuts down the ADC. The ADC must be disabled before shut down. The analog comparator cannot use the ADC input MUX when the ADC is shut down.
31
8263A-AVR-08/10
8. System Control and Reset
8.1 Resetting the AVR
During reset, all I/O registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a RJMP - Relative Jump - instruction to the reset handling routine. If the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. The circuit diagram in Figure 8-1 shows the reset logic. Electrical parameters of the reset circuitry are defined in section "System and Reset Characteristics" on page 168. Figure 8-1. Reset Logic
DATA BUS
BODLEVEL[2:0]
RESET FLAG REGISTER (RSTFLR)
BORF PORF EXTRF WDRF
VCC
BROWN OUT RESET CIRCUIT PULL-UP RESISTOR SPIKE FILTER EXTERNAL RESET CIRCUIT
CK
POWER-ON RESET CIRCUIT
S
COUNTER RESET TIMEOUT
Q
INTERNAL RESET
RESET
R
DELAY COUNTERS
WATCHDOG TIMER
RSTDISBL WATCHDOG OSCILLATOR CLOCK GENERATOR
The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not require any clock source to be running. After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the power to reach a stable level before normal operation starts. The start up sequence is described in "Starting from Reset" on page 22.
8.2
Reset Sources
The ATtiny40 has four sources of reset: * Power-on Reset. The MCU is reset when the supply voltage is below the Power-on Reset threshold (VPOT) * External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum pulse length * Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled * Brown Out Reset. The MCU is reset when the Brown-Out Detector is enabled and supply voltage is below the brown-out threshold (VBOT)
8.2.1
Power-on Reset A Power-on Reset (POR) pulse is generated by an on-chip detection circuit. The detection level is defined in section "System and Reset Characteristics" on page 168. The POR is activated whenever VCC is below the detection level. The POR circuit can be used to trigger the Start-up Reset, as well as to detect a failure in supply voltage. A Power-on Reset (POR) circuit ensures that the device is reset from Power-on. Reaching the Power-on Reset threshold voltage invokes the delay counter, which determines how long the
32
ATtiny40
8263A-AVR-08/10
ATtiny40
device is kept in reset after VCC rise. The reset signal is activated again, without any delay, when VCC decreases below the detection level. Figure 8-2.
V CC
MCU Start-up, RESET High before Initial Time-out
V POT
RESET
V RST
TIME-OUT
t TOUT
INTERNAL RESET
Figure 8-3.
V CC
MCU Start-up, RESET Extended Externally
V POT > t TOUT
RESET
V RST
TIME-OUT
t TOUT
INTERNAL RESET
8.2.2
External Reset An External Reset is generated by a low level on the RESET pin if enabled. Reset pulses longer than the minimum pulse width (see section "System and Reset Characteristics" on page 168) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage - VRST - on its positive edge, the delay counter starts the MCU after the time-out period - tTOUT - has expired. External reset is ignored during Power-on start-up count. After Power-on reset the internal reset is extended only if RESET pin is low when the initial Power-on delay count is complete. See Figure 8-2 and Figure 8-3.
33
8263A-AVR-08/10
Figure 8-4.
CC
External Reset During Operation
8.2.3
Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the time-out period tTOUT. See page 34 for details on operation of the Watchdog Timer and Table 21-4 on page 168 for details on reset time-out. Figure 8-5.
CC
Watchdog Reset During Operation
CK
8.2.4
Brown-out Detection ATtiny40 has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during operation by comparing it to a fixed trigger level. The trigger level for the BOD can be selected by the BODLEVEL Fuses. The trigger level has a hysteresis to ensure spike free Brown-out Detection. The hysteresis on the detection level should be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2. When the BOD is enabled, and VCC decreases to a value below the trigger level (VBOT- in Figure 8-6 on page 35), the Brown-out Reset is immediately activated. When VCC increases above the trigger level (VBOT+ in Figure 8-6), the delay counter starts the MCU after the Time-out period tTOUT has expired. The BOD circuit will only detect a drop in VCC if the voltage stays below the trigger level for longer than tBOD given in "System and Reset Characteristics" on page 168.
34
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 8-6. Brown-out Reset During Operation
VCC
VBOT-
VBOT+
RESET
TIME-OUT
tTOUT
INTERNAL RESET
8.3
Internal Voltage Reference
ATtiny40 features an internal bandgap reference. This reference is used for Brown-out Detection, and it can be used as an input to the Analog Comparator or the ADC. The bandgap voltage varies with supply voltage and temperature.
8.3.1
Voltage Reference Enable Signals and Start-up Time The voltage reference has a start-up time that may influence the way it should be used. The start-up time is given in "System and Reset Characteristics" on page 168. To save power, the reference is not always turned on. The reference is on during the following situations: 1. When the BOD is enabled (by programming the BODLEVEL[2:0] Fuse). 2. When the internal reference is connected to the Analog Comparator (by setting the ACBG bit in ACSR). 3. When the ADC is enabled. Thus, when the BOD is not enabled, after setting the ACBG bit or enabling the ADC, the user must always allow the reference to start up before the output from the Analog Comparator or ADC is used. To reduce power consumption in Power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering Power-down mode.
8.4
Watchdog Timer
The Watchdog Timer is clocked from an on-chip oscillator, which runs at 128 kHz. See Figure 87. By controlling the Watchdog Timer prescaler, the Watchdog Reset interval can be adjusted as shown in Table 8-2 on page 38. The WDR - Watchdog Reset - instruction resets the Watchdog Timer. The Watchdog Timer is also reset when it is disabled and when a device reset occurs. Ten different clock cycle periods can be selected to determine the reset period. If the reset period expires without another Watchdog Reset, the ATtiny40 resets and executes from the Reset Vector. For timing details on the Watchdog Reset, refer to Table 8-3 on page 38.
35
8263A-AVR-08/10
Figure 8-7.
Watchdog Timer
128 kHz OSCILLATOR OSC/2K OSC/4K OSC/8K
WATCHDOG PRESCALER OSC/1024K OSC/128K OSC/256K OSC/512K OSC/16K OSC/32K OSC/64K
WATCHDOG RESET WDP0 WDP1 WDP2 WDP3 WDE
MUX
MCU RESET
The Wathdog Timer can also be configured to generate an interrupt instead of a reset. This can be very helpful when using the Watchdog to wake-up from Power-down. To prevent unintentional disabling of the Watchdog or unintentional change of time-out period, two different safety levels are selected by the fuse WDTON as shown in Table 8-1 on page 36. See "Procedure for Changing the Watchdog Timer Configuration" on page 36 for details. Table 8-1.
WDTON Unprogrammed Programmed
WDT Configuration as a Function of the Fuse Settings of WDTON
Safety Level 1 2 WDT Initial State Disabled Enabled How to Disable the WDT Protected change sequence Always enabled How to Change Time-out No limitations Protected change sequence
8.4.1
Procedure for Changing the Watchdog Timer Configuration The sequence for changing configuration differs between the two safety levels, as follows: Safety Level 1 In this mode, the Watchdog Timer is initially disabled, but can be enabled by writing the WDE bit to one without any restriction. A special sequence is needed when disabling an enabled Watchdog Timer. To disable an enabled Watchdog Timer, the following procedure must be followed: 1. Write the signature for change enable of protected I/O registers to register CCP 2. Within four instruction cycles, in the same operation, write WDE and WDP bits
8.4.1.1
8.4.1.2
Safety Level 2 In this mode, the Watchdog Timer is always enabled, and the WDE bit will always read as one. A protected change is needed when changing the Watchdog Time-out period. To change the Watchdog Time-out, the following procedure must be followed: 1. Write the signature for change enable of protected I/O registers to register CCP 2. Within four instruction cycles, write the WDP bit. The value written to WDE is irrelevant
36
ATtiny40
8263A-AVR-08/10
ATtiny40
8.4.2 Code Examples The following code example shows how to turn off the WDT. The example assumes that interrupts are controlled (e.g., by disabling interrupts globally) so that no interrupts will occur during execution of these functions. Assembly Code Example
WDT_off: wdr ; Clear WDRF in RSTFLR in andi out r16, RSTFLR r16, ~(1<; Write signature for change enable of protected I/O register ldi r16, 0xD8 out CCP, r16 ; Within four instruction cycles, turn off WDT ldi r16, (0<8.5
8.5.1
Register Description
WDTCSR - Watchdog Timer Control and Status Register
Bit 0x31 Read/Write Initial Value 7 WDIF R/W 0 6 WDIE R/W 0 5 WDP3 R/W 0 4 - R 0 3 WDE R/W X 2 WDP2 R/W 0 1 WDP1 R/W 0 0 WDP0 R/W 0 WDTCSR
* Bit 7 - WDIF: Watchdog Timer Interrupt Flag This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WDIF is cleared by writing a logic one to the flag. When the WDIE is set, the Watchdog Time-out Interrupt is requested. * Bit 6 - WDIE: Watchdog Timer Interrupt Enable When this bit is written to one, the Watchdog interrupt request is enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt Mode, and the corresponding interrupt is requested if time-out in the Watchdog Timer occurs. If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and System Reset Mode, WDIE must be set after each interrupt. This should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the
37
8263A-AVR-08/10
Watchdog System Reset mode. If the interrupt is not executed before the next time-out, a System Reset will be applied. Table 8-2.
WDTON 1 1 1 1 0 Note:
(1)
Watchdog Timer Configuration
WDE 0 0 1 1 x WDIE 0 1 0 1 x Mode Stopped Interrupt System Reset Interrupt and System Reset System Reset Action on Time-out None Interrupt Reset Interrupt, then go to System Reset Mode Reset
1. WDTON configuration bit set to "0" means programmed and "1" means unprogrammed.
* Bit 4 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 3 - WDE: Watchdog System Reset Enable WDE is overridden by WDRF in RSTFLR. This means that WDE is always set when WDRF is set. To clear WDE, WDRF must be cleared first. This feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure. * Bits 5, 2:0 - WDP[3:0]: Watchdog Timer Prescaler 3, 2, 1 and 0 The WDP[3:0] bits determine the Watchdog Timer prescaling when the Watchdog Timer is running. The different prescaling values and their corresponding time-out periods are shown in Table 8-3 on page 38. Table 8-3.
WDP3 0 0 0 0 0 0 0 0 1 1
Watchdog Timer Prescale Select
WDP2 0 0 0 0 1 1 1 1 0 0 WDP1 0 0 1 1 0 0 1 1 0 0 WDP0 0 1 0 1 0 1 0 1 0 1 Number of WDT Oscillator Cycles 2K (2048) cycles 4K (4096) cycles 8K (8192) cycles 16K (16384) cycles 32K (32768) cycles 64K (65536) cycles 128K (131072) cycles 256K (262144) cycles 512K (524288) cycles 1024K (1048576) cycles Typical Time-out at VCC = 5.0V 16 ms 32 ms 64 ms 0.125 s 0.25 s 0.5 s 1.0 s 2.0 s 4.0 s 8.0 s
38
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 8-3.
WDP3 1 1 1 1 1 1
Watchdog Timer Prescale Select (Continued)
WDP2 0 0 1 1 1 1 WDP1 1 1 0 0 1 1 WDP0 0 1 0 1 0 1 Reserved Number of WDT Oscillator Cycles Typical Time-out at VCC = 5.0V
8.5.2
RSTFLR - Reset Flag Register The Reset Flag Register provides information on which reset source caused an MCU Reset.
Bit 0x3B Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 WDRF R/W X 2 BORF R/W X 1 EXTRF R/W X 0 PORF R/W X RSTFLR
* Bits 7:4 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 3 - WDRF: Watchdog Reset Flag This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 2 - BORF: Brown-Out Reset Flag This bit is set if a Brown-Out Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 1 - EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 0 - PORF: Power-On Reset Flag This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag. To make use of the Reset Flags to identify a reset condition, the user should read and then reset the RSTFLR as early as possible in the program. If the register is cleared before another reset occurs, the source of the reset can be found by examining the Reset Flags.
39
8263A-AVR-08/10
9. Interrupts
This section describes the specifics of the interrupt handling as performed in ATtiny40. For a general explanation of the AVR interrupt handling, see "Reset and Interrupt Handling" on page 11.
9.1
Interrupt Vectors
The interrupt vectors of ATtiny40 are described in Table 9-1 below. Table 9-1.
Vector No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1.
Reset and Interrupt Vectors
Program Address 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 0x0009 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0010 0x0011 Label RESET INT0 PCINT0 PCINT1 PCINT2 WDT TIM1_CAPT TIM1_COMPA TIM1_COMPB TIM1_OVF TIM0_COMPA TIM0_COMPB TIM0_OVF ANA_COMP ADC TWI_SLAVE SPI QTRIP
(1)
Interrupt Source External Pin, Power-on Reset, Brown-Out Reset, Watchdog Reset External Interrupt Request 0 Pin Change Interrupt Request 0 Pin Change Interrupt Request 1 Pin Change Interrupt Request 2 Watchdog Time-out Timer/Counter1 Input Capture Timer/Counter1 Compare Match A Timer/Counter1 Compare Match B Timer/Counter1 Overflow Timer/Counter0 Compare Match A Timer/Counter0 Compare Match B Timer/Counter0 Overflow Analog Comparator ADC Conversion Complete Two-Wire Interface Serial Peripheral Interface Touch Sensing
The touch sensing interrupt source is related to the QTouch library support.
In case the program never enables an interrupt source, the Interrupt Vectors will not be used and, consequently, regular program code can be placed at these locations. The most typical and general setup for interrupt vector addresses in ATtiny40 is shown in the program example below.
Address Labels Code 0x0000 0x0001 0x0002 rjmp rjmp rjmp RESET INT0 PCINT0
Comments ; Reset Handler ; IRQ0 Handler ; PCINT0 Handler
40
ATtiny40
8263A-AVR-08/10
ATtiny40
0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 0x0009 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0010 0x0011 0x0012 0x0013 0x0014 0x0015 0x0016 0x0017 ... rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp rjmp RESET: ldi out ldi out sei ... PCINT1 PCINT2 WDT TIM1_CAPT TIM1_COMPA TIM1_COMPB TIM1_OVF TIM0_COMPA TIM0_COMPB TIM0_OVF ANA_COMP ADC TWI_SLAVE SPI QTRIP ; PCINT1 Handler ; PCINT2 Handler ; Watchdog Interrupt Handler ; Timer1 Capture Handler ; Timer1 Compare A Handler ; Timer1 Compare B Handler ; Timer1 Overflow Handler ; Timer0 Compare A Handler ; Timer0 Compare B Handler ; Timer0 Overflow Handler ; Analog Comparator Handler ; ADC Conversion Handler ; Two-Wire Interface Handler ; Serial Peripheral Interface Handler ; Touch Sensing Handler
r16, high(RAMEND); Main program start SPH,r16 SPL,r16 ; Enable interrupts ; Set Stack Pointer r16, low(RAMEND) ; to top of RAM
9.2
External Interrupts
External Interrupts are triggered by the INT0 pin or any of the PCINT[17:0] pins. Observe that, if enabled, the interrupts will trigger even if the INT0 or PCINT[17:0] pins are configured as outputs. This feature provides a way of generating a software interrupt. Pin change 0 interrupts PCI0 will trigger if any enabled PCINT[7:0] pin toggles. Pin change 1 interrupts PCI1 will trigger if any enabled PCINT[11:8] pin toggles. Pin change 2 interrupts PCI1 will trigger if any enabled PCINT[17:12] pin toggles. The PCMSK0, PCMSK1 and PCMSK2 Registers control which pins contribute to the pin change interrupts. Pin change interrupts on PCINT[17:0] are detected asynchronously, which means that these interrupts can be used for waking the part also from sleep modes other than Idle mode. The INT0 interrupt can be triggered by a falling or rising edge or a low level. This is set up as shown in "MCUCR - MCU Control Register" on page 43. When the INT0 interrupt is enabled and configured as level triggered, the interrupt will trigger as long as the pin is held low. Note that recognition of falling or rising edge interrupts on INT0 requires the presence of an I/O clock, as described in "Clock System" on page 20.
9.2.1
Low Level Interrupt A low level interrupt on INT0 is detected asynchronously. This means that the interrupt source can be used for waking the part also from sleep modes other than Idle (the I/O clock is halted in all sleep modes except Idle).
41
8263A-AVR-08/10
Note that if a level triggered interrupt is used for wake-up from Power-down, the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined as described in "Clock System" on page 20. If the low level on the interrupt pin is removed before the device has woken up then program execution will not be diverted to the interrupt service routine but continue from the instruction following the SLEEP command. 9.2.2 Pin Change Interrupt Timing A timing example of a pin change interrupt is shown in Figure 9-1. Figure 9-1.
PCINT(0)
LE
Timing of pin change interrupts
pin_lat
D Q
pcint_in_(0) pin_sync PCINT(0) in PCMSK(x)
0 x clk
pcint_syn
pcint_setflag PCIF
clk
clk
PCINT(0)
pin_lat
pin_sync
pcint_in_(0)
pcint_syn
pcint_setflag
PCIF
42
ATtiny40
8263A-AVR-08/10
ATtiny40
9.3
9.3.1
Register Description
MCUCR - MCU Control Register The MCU Control Register contains bits for controlling external interrupt sensing and power management.
Bit 0x3A Read/Write Initial Value 7 ISC01 R/W 0 6 ISC00 R/W 0 5 - R 0 4 BODS R/W 0 3 SM2 R/W 0 2 SM1 R/W 0 1 SM0 R/W 0 0 SE R/W 0 MCUCR
* Bits 7:6 - ISC0[1:0]: Interrupt Sense Control The External Interrupt 0 is activated by the external pin INT0 if the SREG I-flag and the corresponding interrupt mask are set. The level and edges on the external INT0 pin that activate the interrupt are defined in Table 9-2. The value on the INT0 pin is sampled before detecting edges. If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. Table 9-2.
ISC01 0 0 1 1
Interrupt 0 Sense Control
ISC00 0 1 0 1 Description The low level of INT0 generates an interrupt request. Any logical change on INT0 generates an interrupt request. The falling edge of INT0 generates an interrupt request. The rising edge of INT0 generates an interrupt request.
9.3.2
GIMSK - General Interrupt Mask Register
Bit 0x0C Read/Write Initial Value 7 - R 0 6 PCIE2 R/W 0 5 PCIE1 R/W 0 4 PCIE0 R/W 0 3 - R 0 2 - R 0 1 - R 0 0 INT0 R/W 0 GIMSK
* Bit 7 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 6 - PCIE2: Pin Change Interrupt Enable 2 When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 2 is enabled. Any change on any enabled PCINT[17:12] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT[17:12] pins are enabled individually by the PCMSK2 Register. * Bit 5 - PCIE1: Pin Change Interrupt Enable 1 When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 1 is enabled. Any change on any enabled PCINT[11:8] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1 Interrupt Vector. PCINT[11:8] pins are enabled individually by the PCMSK1 Register.
43
8263A-AVR-08/10
* Bit 4 - PCIE0: Pin Change Interrupt Enable 0 When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 0 is enabled. Any change on any enabled PCINT[7:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT[7:0] pins are enabled individually by the PCMSK0 Register. * Bits 3:1 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 0 - INT0: External Interrupt Request 0 Enable When the INT0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), the external pin interrupt is enabled. The Interrupt Sense Control bits (ISC01 and ISC00) in the MCU Control Register (MCUCR) define whether the external interrupt is activated on rising and/or falling edge of the INT0 pin or level sensed. Activity on the pin will cause an interrupt request even if INT0 is configured as an output. The corresponding interrupt of External Interrupt Request 0 is executed from the INT0 Interrupt Vector. 9.3.3 GIFR - General Interrupt Flag Register
Bit 0x0B Read/Write Initial Value 7 - R 0 6 PCIF2 R/W 0 5 PCIF1 R/W 0 4 PCIF0 R/W 0 3 - R 0 2 - R 0 1 - R 0 0 INTF0 R/W 0 GIFR
* Bit 7 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 6 - PCIF2: Pin Change Interrupt Flag 2 When a logic change on any PCINT[17:12] pin triggers an interrupt request, PCIF2 becomes set (one). If the I-bit in SREG and the PCIE2 bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 5 - PCIF1: Pin Change Interrupt Flag 1 When a logic change on any PCINT[11:8] pin triggers an interrupt request, PCIF1 becomes set (one). If the I-bit in SREG and the PCIE1 bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 4 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT[7:0] pin triggers an interrupt request, PCIF becomes set (one). If the I-bit in SREG and the PCIE0 bit in GIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bits 3:1 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 0 - INTF0: External Interrupt Flag 0 When an edge or logic change on the INT0 pin triggers an interrupt request, INTF0 becomes set (one). If the I-bit in SREG and the INT0 bit in GIMSK are set (one), the MCU will jump to the cor44
ATtiny40
8263A-AVR-08/10
ATtiny40
responding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. This flag is always cleared when INT0 is configured as a level interrupt. 9.3.4 PCMSK2 - Pin Change Mask Register 2
Bit 0x1A Read/Write Initial Value 7 - R 0 6 - R 0 5 PCINT17 R/W 0 4 PCINT16 R/W 0 3 PCINT15 R/W 0 2 PCINT14 R/W 0 1 PCINT13 R/W 0 0 PCINT12 R/W 0 PCMSK2
* Bits 7:6 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 5:0 - PCINT[17:12]: Pin Change Enable Mask 17:12 Each PCINT[17:12] bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT[17:12] is set and the PCIE2 bit in GIMSK is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT[17:12] is cleared, pin change interrupt on the corresponding I/O pin is disabled. 9.3.5 PCMSK1 - Pin Change Mask Register 1
Bit 0x0A Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 PCINT11 R/W 0 2 PCINT10 R/W 0 1 PCINT9 R/W 0 0 PCINT8 R/W 0 PCMSK1
* Bits 7:4 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 3:0 - PCINT[11:8]: Pin Change Enable Mask 11:8 Each PCINT[11:8] bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT[11:8] is set and the PCIE1 bit in GIMSK is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT[11:8] is cleared, pin change interrupt on the corresponding I/O pin is disabled. 9.3.6 PCMSK0 - Pin Change Mask Register 0
Bit 0x09 Read/Write Initial Value 7 PCINT7 R/W 0 6 PCINT6 R/W 0 5 PCINT5 R/W 0 4 PCINT4 R/W 0 3 PCINT3 R/W 0 2 PCINT2 R/W 0 1 PCINT1 R/W 0 0 PCINT0 R/W 0 PCMSK0
* Bits 7:0 - PCINT[7:0]: Pin Change Enable Mask 7:0 Each PCINT[7:0] bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT[7:0] is set and the PCIE0 bit in GIMSK is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT[7:0] is cleared, pin change interrupt on the corresponding I/O pin is disabled.
45
8263A-AVR-08/10
10. I/O Ports
10.1 Overview
All AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors. Each output buffer has symmetrical drive characteristics with both high sink and source capability. The pin driver is strong enough to drive LED displays directly. All port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VCC and Ground as indicated in Figure 10-1 on page 46. See "Electrical Characteristics" on page 165 for a complete list of parameters. Figure 10-1. I/O Pin Equivalent Schematic
Rpu
Pxn
Logic Cpin
See Figure "General Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case "x" represents the numbering letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description" on page 62. Four I/O memory address locations are allocated for each port, one each for the Data Register - PORTx, Data Direction Register - DDRx, Pull-up Enable Register - PUEx, and the Port Input Pins - PINx. The Port Input Pins I/O location is read only, while the Data Register, the Data Direction Register, and the Pull-up Enable Register are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. Using the I/O port as General Digital I/O is described in "Ports as General Digital I/O" on page 47. Most port pins are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes with the port pin is described in "Alternate Port Functions" on page 52. Refer to the individual module sections for a full description of the alternate functions. Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital I/O.
46
ATtiny40
8263A-AVR-08/10
ATtiny40
10.2 Ports as General Digital I/O
The ports are bi-directional I/O ports with optional internal pull-ups. Figure 10-2 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 10-2. General Digital I/O(1)
REx
Q
D
PUExn Q CLR
RESET
WEx
Q
D
DDxn Q CLR
RESET
WDx RDx
1 Pxn
Q D PORTxn Q CLR
0
RESET WRx SLEEP RRx
WPx
SYNCHRONIZER
D Q D Q
RPx
PINxn L Q Q
clk I/O WEx: REx: WDx: RDx: WRx: RRx: RPx: WPx: WRITE PUEx READ PUEx WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN WRITE PINx REGISTER
SLEEP: clk I/O :
SLEEP CONTROL I/O CLOCK
Note:
1. WEx, WRx, WPx, WDx, REx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, and SLEEP are common to all ports.
10.2.1
Configuring the Pin Each port pin consists of four register bits: DDxn, PORTxn, PUExn, and PINxn. As shown in "Register Description" on page 62, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, the PUExn bits at the PUEx I/O address, and the PINxn bits at the PINx I/O address.
8263A-AVR-08/10
DATA BUS
47
The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin. If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). The pull-up resistor is activated, if the PUExn is written logic one. To switch the pull-up resistor off, PUExn has to be written logic zero. Table 10-1 summarizes the control signals for the pin value. Table 10-1.
DDxn 0 0 1
Port Pin Configurations
PUExn I/O Input Input Output Pull-up No Yes No Comment Tri-state (hi-Z) Sources current if pulled low externally Output low (sink) NOT RECOMMENDED. Output low (sink) and internal pull-up active. Sources current through the internal pull-up resistor and consumes power constantly Output high (source) Output high (source) and internal pull-up active X X 0
PORTxn
0 1 0 1 0 1
1
0
Output
Yes
1 1
1 1
Output Output
No Yes
Port pins are tri-stated when a reset condition becomes active, even when no clocks are running. 10.2.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. Break-Before-Make Switching In Break-Before-Make mode, switching the DDRxn bit from input to output introduces an immediate tri-state period lasting one system clock cycle, as indicated in Figure 10-3. For example, if the system clock is 4 MHz and the DDRxn is written to make an output, an immediate tri-state period of 250 ns is introduced before the value of PORTxn is seen on the port pin. To avoid glitches it is recommended that the maximum DDRxn toggle frequency is two system clock cycles. The Break-Before-Make mode applies to the entire port and it is activated by the BBMx bit. For more details, see "PORTCR - Port Control Register" on page 62. When switching the DDRxn bit from output to input no immediate tri-state period is introduced.
10.2.3
48
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 10-3. Switching Between Input and Output in Break-Before-Make-Mode
SYSTEM CLK r16 r17 INSTRUCTIONS PORTx DDRx Px0 Px1
tri-state
intermediate tri-state cycle
0x02 0x01 out DDRx, r16 nop 0x55 0x01 0x02 tri-state tri-state
intermediate tri-state cycle
out DDRx, r17
0x01
10.2.4
Reading the Pin Value Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As shown in Figure 10-2 on page 47, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. Figure 10-4 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively. Figure 10-4. Synchronization when Reading an Externally Applied Pin value
SYSTEM CLK INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd, max t pd, min 0xFF XXX XXX in r17, PINx
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the "SYNC LATCH" signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between 1/2 and 11/2 system clock period depending upon the time of assertion. 49
8263A-AVR-08/10
When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 10-5 on page 50. The out instruction sets the "SYNC LATCH" signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is one system clock period. Figure 10-5. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK r16 INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd 0xFF out PORTx, r16 nop 0xFF
in r17, PINx
10.2.5
Digital Input Enable and Sleep Modes As shown in Figure 10-2 on page 47, the digital input signal can be clamped to ground at the input of the schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down and Standby modes to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2. SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in "Alternate Port Functions" on page 52. If a logic high level ("one") is present on an asynchronous external interrupt pin configured as "Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin" while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these sleep mode produces the requested logic change.
10.2.6
Unconnected Pins If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pulldown. Connecting unused pins directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.
50
ATtiny40
8263A-AVR-08/10
ATtiny40
10.2.7 Program Example The following code example shows how to set port B pin 0 high, pin 1 low, and define the port pins from 2 to 3 as input with a pull-up assigned to port pin 2. The resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. Assembly Code Example
... ; Define pull-ups and set outputs high ; Define directions for port pins ldi ldi ldi out out out nop ; Read port pins in ... Note: See "Code Examples" on page 6. r16,PINB r16,(1<; Insert nop for synchronization
51
8263A-AVR-08/10
10.3
Alternate Port Functions
Most port pins have alternate functions in addition to being general digital I/Os. In Figure 10-6 below is shown how the port pin control signals from the simplified Figure 10-2 on page 47 can be overridden by alternate functions. Figure 10-6. Alternate Port Functions(1)
PUOExn PUOVxn
1 0
Q D
REx
PUExn Q CLR
DDOExn RESET DDOVxn
1 0
Q D DDxn Q CLR
WEx
PVOExn PVOVxn
WDx RESET RDx
1 Pxn 0
Q D
1 0
PORTxn
PTOExn WPx
DIEOExn DIEOVxn
1 0
Q CLR
RESET RRx
WRx
SLEEP SYNCHRONIZER
D
SET
RPx
Q
Q
D
PINxn L
CLR
Q
CLR
Q
clk
I/O
DIxn
AIOxn WEx: REx: WDx: RDx: RRx: WRx: RPx: WPx: clk I/O : DIxn: AIOxn: WRITE PUEx READ PUEx WRITE DDRx READ DDRx READ PORTx REGISTER WRITE PORTx READ PORTx PIN WRITE PINx I/O CLOCK DIGITAL INPUT PIN n ON PORTx ANALOG INPUT/OUTPUT PIN n ON PORTx
PUOExn: PUOVxn: DDOExn: DDOVxn: PVOExn: PVOVxn: DIEOExn: DIEOVxn: SLEEP: PTOExn:
Pxn PULL-UP OVERRIDE ENABLE Pxn PULL-UP OVERRIDE VALUE Pxn DATA DIRECTION OVERRIDE ENABLE Pxn DATA DIRECTION OVERRIDE VALUE Pxn PORT VALUE OVERRIDE ENABLE Pxn PORT VALUE OVERRIDE VALUE Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE SLEEP CONTROL Pxn, PORT TOGGLE OVERRIDE ENABLE
Note:
1. WEx, WRx, WPx, WDx, REx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, and SLEEP are common to all ports. All other signals are unique for each pin.
52
ATtiny40
8263A-AVR-08/10
DATA BUS
ATtiny40
The illustration in the figure above serves as a generic description applicable to all port pins in the AVR microcontroller family. Some overriding signals may not be present in all port pins. Table 10-2 on page 53 summarizes the function of the overriding signals. The pin and port indexes from Figure 10-6 on page 52 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function. Table 10-2.
Signal Name PUOE
Generic Description of Overriding Signals for Alternate Functions
Full Name Pull-up Override Enable Pull-up Override Value Data Direction Override Enable Data Direction Override Value Description If this signal is set, the pull-up enable is controlled by the PUOV signal. If this signal is cleared, the pull-up is enabled when PUExn = 0b1. If PUOE is set, the pull-up is enabled/disabled when PUOV is set/cleared, regardless of the setting of the PUExn Register bit. If this signal is set, the Output Driver Enable is controlled by the DDOV signal. If this signal is cleared, the Output driver is enabled by the DDxn Register bit. If DDOE is set, the Output Driver is enabled/disabled when DDOV is set/cleared, regardless of the setting of the DDxn Register bit. If this signal is set and the Output Driver is enabled, the port value is controlled by the PVOV signal. If PVOE is cleared, and the Output Driver is enabled, the port Value is controlled by the PORTxn Register bit. If PVOE is set, the port value is set to PVOV, regardless of the setting of the PORTxn Register bit. If PTOE is set, the PORTxn Register bit is inverted. If this bit is set, the Digital Input Enable is controlled by the DIEOV signal. If this signal is cleared, the Digital Input Enable is determined by MCU state (Normal mode, sleep mode). If DIEOE is set, the Digital Input is enabled/disabled when DIEOV is set/cleared, regardless of the MCU state (Normal mode, sleep mode). This is the Digital Input to alternate functions. In the figure, the signal is connected to the output of the schmitt-trigger but before the synchronizer. Unless the Digital Input is used as a clock source, the module with the alternate function will use its own synchronizer. This is the Analog Input/Output to/from alternate functions. The signal is connected directly to the pad, and can be used bidirectionally.
PUOV
DDOE
DDOV
PVOE
Port Value Override Enable Port Value Override Value Port Toggle Override Enable Digital Input Enable Override Enable Digital Input Enable Override Value
PVOV PTOE
DIEOE
DIEOV
DI
Digital Input
AIO
Analog Input/Output
The following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. Refer to the alternate function description for further details.
53
8263A-AVR-08/10
10.3.1
Alternate Functions of Port A The Port A pins with alternate function are shown in Table 10-3. Table 10-3. Port A Pins Alternate Functions
Alternate Function ADC0: ADC Input Channel 0 PCINT0: Pin Change Interrupt 0, Source 0 ADC1: ADC Input Channel 1 AIN0: Analog Comparator, Positive Input PCINT1:Pin Change Interrupt 0, Source 1 ADC2: ADC Input Channel 2 AIN1: Analog Comparator, Negative Input PCINT2: Pin Change Interrupt 0, Source 2 ADC3: ADC Input Channel 3 PCINT3: Pin Change Interrupt 0, Source 3 ADC4: ADC Input Channel 4 T0: Timer/Counter0 Clock Source PCINT4: Pin Change Interrupt 0, Source 4 ADC5: ADC Input Channel 5 OC0B: Timer/Counter0 Compare Match B Output PCINT5: Pin Change Interrupt 0, Source 5 ADC6: ADC Input Channel 6 PCINT6: Pin Change Interrupt 0, Source 6 ADC7: ADC Input Channel 7 PCINT7: Pin Change Interrupt 0, Source 7
Port Pin PA0
PA1
PA2
PA3
PA4
PA5
PA6 PA7
* Port A, Bit 0 - ADC0/PCINT0 * ADC0: Analog to Digital Converter, Channel 0. * PCINT0: Pin Change Interrupt source 0. The PA0 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 1 - ADC1/AIN0/PCINT1 * ADC1: Analog to Digital Converter, Channel 1. * AIN0: Analog Comparator Positive Input. Configure the port pin as input with the internal pullup switched off to avoid the digital port function from interfering with the function of the Analog Comparator. * PCINT1: Pin Change Interrupt source 1. The PA1 pin can serve as an external interrupt source for pin change interrupt 0.
54
ATtiny40
8263A-AVR-08/10
ATtiny40
* Port A, Bit 2 - ADC2/AIN1/PCINT2 * ADC2: Analog to Digital Converter, Channel 2. * AIN1: Analog Comparator Negative Input. Configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the Analog Comparator. * PCINT2: Pin Change Interrupt source 2. The PA2 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 3 - ADC3/PCINT3 * ADC3: Analog to Digital Converter, Channel 3. * PCINT3: Pin Change Interrupt source 3. The PA3 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 4 - ADC4/T0/PCINT4 * ADC4: Analog to Digital Converter, Channel 4. * T0: Timer/Counter0 counter source. * PCINT4: Pin Change Interrupt source 4. The PA4 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 5 - ADC5/OC0B/PCINT5 * ADC5: Analog to Digital Converter, Channel 5. * OC0B: Output Compare Match output. The PA5 pin can serve as an external output for the Timer/Counter0 Compare Match B. The pin has to be configured as an output (DDA5 set (one)) to serve this function. This is also the output pin for the PWM mode timer function. * PCINT5: Pin Change Interrupt source 5. The PA5 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 6 - ADC6/PCINT6 * ADC6: Analog to Digital Converter, Channel 6. * PCINT6: Pin Change Interrupt source 6. The PA6 pin can serve as an external interrupt source for pin change interrupt 0. * Port A, Bit 7 - ADC7/PCINT7 * ADC7: Analog to Digital Converter, Channel 7. * PCINT7: Pin Change Interrupt source 7. The PA7 pin can serve as an external interrupt source for pin change interrupt 0.
55
8263A-AVR-08/10
Table 10-4 and Table 10-5 relate the alternate functions of Port A to the overriding signals shown in Figure 10-6 on page 52. Table 10-4.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO Note:
Overriding Signals for Alternate Functions in PA[7:5]
PA7/ADC7/PCINT7 0 0 0 0 0 0 0 PCINT7 * PCIE0 + ADC7D PCINT7 * PCIE0 PCINT7 Input ADC7 Input PA6/ADC6/PCINT6 0 0 0 0 0 0 0 PCINT6 * PCIE0 + ADC6D PCINT6 * PCIE0 PCINT6 Input ADC6 Input PA5/ADC5/PCINT5 0 0 0 0 OC0B_ENABLE OC0B 0 PCINT5 * PCIE0 + ADC5D PCINT5 * PCIE0 PCINT5 Input ADC5 Input
When TWI is enabled the slew rate control and spike filter are activated on PA7. This is not illustrated in Figure 10-6 on page 52. The spike filter is connected between AIOxn and the TWI module.
Table 10-5.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PA[4:2]
PA4/ADC4/PCINT4 0 0 0 0 0 0 0 PA3/ADC3/PCINT3 0 0 0 0 0 0 0 (PCINT3 * PCIE0) + ADC3D PCINT3 * PCIE0 PCINT1 Input ADC3 Input PA2/ADC2/AIN1/PCINT2 0 0 0 0 0 0 0 (PCINT2 * PCIE0) + ADC2D PCINT3 * PCIE0 PCINT0 Input ADC2 / Analog Comparator Negative Input
(PCINT4 * PCIE0) + ADC4D PCINT4 * PCIE0 T0 / PCINT4 input ADC4 Input
56
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 10-6.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PA[1:0]
PA1/ADC1/AIN0/PCINT1 0 0 0 0 0 0 0 PCINT1 * PCIE0 + ADC1D PCINT1 * PCIE0 PCINT1 Input ADC1 / Analog Comparator Positive Input PA0/ADC0/PCINT0 0 0 0 0 0 0 0 PCINT0 * PCIE0 + ADC0D PCINT0 * PCIE0 PCINT0 Input ADC1 Input
10.3.2
Alternate Functions of Port B The Port B pins with alternate function are shown in Table 10-7. Table 10-7. Port B Pins Alternate Functions
Alternate Function ADC8: ADC Input Channel 8 PCINT8: Pin Change Interrupt 1, Source 8 ADC9: ADC Input Channel 9 PCINT9: Pin Change Interrupt 1, Source 9 ADC10: ADC Input Channel 10 PCINT10:Pin Change Interrupt 1, Source 10 ADC11: ADC Input Channel 11 PCINT11:Pin Change Interrupt 1, Source 11.
Port Pin PB0 PB1 PB2 PB3
* Port B, Bit 0 - ADC8/PCINT8 * ADC8: Analog to Digital Converter, Channel 8. * PCINT8: Pin Change Interrupt source 8. The PB0 pin can serve as an external interrupt source for pin change interrupt 1. * Port B, Bit 1 - ADC9/PCINT9 * ADC9: Analog to Digital Converter, Channel 9. * PCINT9: Pin Change Interrupt source 9. The PB1 pin can serve as an external interrupt source for pin change interrupt 1. * Port B, Bit 2 - ADC10/PCINT10 * ADC10: Analog to Digital Converter, Channel 10.
57
8263A-AVR-08/10
* PCINT10: Pin Change Interrupt source 10. The PB2 pin can serve as an external interrupt source for pin change interrupt 1. * Port B, Bit 3 - ADC11/PCINT11 * ADC11: Analog to Digital Converter, Channel 11. * PCINT11: Pin Change Interrupt source 11. The PB3 pin can serve as an external interrupt source for pin change interrupt 1. Table 10-8 on page 58 and Table 10-9 on page 58 relate the alternate functions of Port B to the overriding signals shown in Figure 10-6 on page 52. Table 10-8.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB[3:2]
PB3/ADC11/PCINT11 0 0 0 0 0 0 0 PCINT11 * PCIE1 * ADC11D PCINT11 * PCIE1 PCINT11 Input ASDC11 Input PB2/ADC10/PCINT10 0 0 0 0 0 0 0 PCINT10 * PCIE1 * ADC10D PCINT10 * PCIE1 INT0 / PCINT10 / SPI Master Input ADC10 Input
Table 10-9.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB[1:0]
PB1/ADC9/PCINT9 0 0 0 0 0 0 0 PCINT9 * PCIE1 * ADC9D PCINT9 * PCIE1 PCINT9 ADC9 Input PB0/ADC8/PCINT8 0 0 0 0 0 0 0 PCINT8 * PCIE1 * ADC8D PCINT8 * PCIE1 PCINT8 ADC8 Input
58
ATtiny40
8263A-AVR-08/10
ATtiny40
10.3.3 Alternate Functions of Port C The Port C pins with alternate function are shown in Table 10-10. Table 10-10. Port A Pins Alternate Functions
Port Pin PC0 Alternate Function OC0A: Timer/Counter0 Compare Match A output SS : SPI Slave Select PCINT12:Pin Change Interrupt 0, Source 12 SCK: SPI Clock SCL : TWI Clock ICP1: Timer/Counter1 Input Capture Pin T1: Timer/Counter1 Clock Source PCINT13:Pin Change Interrupt 0, Source 13 INT0: External Interrupt 0 Input CLKO: System Clock Output MISO: SPI Master Input / Slave Output PCINT14:Pin Change Interrupt 0, Source 14 RESET: Reset pin PCINT15:Pin Change Interrupt 0, Source 15 MOSI: SPI Master Output / Slave Input SDA: TWI Data Input /Output TPIDATA:Serial Programming Data PCINT16:Pin Change Interrupt 0, Source 16 CLKI: External Clock Input TPICLK: Serial Programming Clock PCINT17:Pin Change Interrupt 0, Source 17
PC1
PC2
PC3
PC4
PC5
* Port C, Bit 0 - OC0A/PCINT12 * OC0A: Output Compare Match output. Provided that the pin has been configured as an output it serves as an external output for Timer/Counter0 Compare Match A. This pin is also the output for the timer/counter PWM mode function. * SS: Slave Select Input. Regardless of DDC0, this pin is automatically configured as an input when SPI is enabled as a slave. The data direction of this pin is controlled by DDC0 when SPI is enabled as a master. * PCINT12: Pin Change Interrupt source 12. The PC0 pin can serve as an external interrupt source for pin change interrupt 2. * Port C, Bit 1 - SCK/SCL/ICP1/T1/PCINT13 * SCK: SPI Clock. * SCL: TWI Clock. The pin is disconnected from the part and becomes the serial clock for the TWI when TWEN in TWSCRA is set. In this mode of operation, the pin is driven by an open drain driver with slew rate limitation and a spike filter. * ICP1: Timer/Counter1 Input Capture Pin. * T1: Timer/Counter1 counter source. * PCINT13: Pin Change Interrupt source 13. The PC1 pin can serve as an external interrupt source for pin change interrupt 2.
59
8263A-AVR-08/10
* Port C, Bit 2 - INT0/CLKO/MISO/PCINT14 * INT0: The PC2 pin can serve as an External Interrupt source 0. * CLKO: The divided system clock can be output on the PB5 pin, if the CKOUT Fuse is programmed, regardless of the PORTB5 and DDB5 settings. It will also be output during reset. * MISO: SPI Master Input / Slave Output. Regardless of DDC2, this pin is automatically configured as an input when SPI is enabled as a master. The data direction of this pin is controlled by DDC2 when SPI is enabled as a slave. * PCINT14: Pin Change Interrupt source 14. The PC2 pin can serve as an external interrupt source for pin change interrupt 2. * Port C, Bit 3 - RESET/PCINT15 * RESET: External Reset input is active low and enabled by unprogramming ("1") the RSTDISBL Fuse. Pullup is activated and output driver and digital input are deactivated when the pin is used as the RESET pin. * PCINT15: Pin Change Interrupt source 15. The PC3 pin can serve as an external interrupt source for pin change interrupt 2. * Port C, Bit 4 - MOSI/SDA/TPIDATA/PCINT16 * MOSI: SPI Master Output / Slave Input. Regardless of DDC4, this pin is automatically configured as an input when SPI is enabled as a slave. The data direction of this pin is controlled by DDC4 when SPI is enabled as a master. * SDA: TWI Data. The pin is disconnected from the port and becomes the serial data for the TWI when TWEN in TWSCRA is set. In this mode of operation, the pin is driven by an open drain driver with slew rate limitation and a spike filter. * TPIDATA: Serial Programming Data. * PCINT16: Pin Change Interrupt source 16. The PC4 pin can serve as an external interrupt source for pin change interrupt 2. * Port C, Bit 5 - CLKI/PCINT17 * CLKI: Clock Input from an external clock source, see "External Clock" on page 21. * TPICLK: Serial Programming Clock. * PCINT17: Pin Change Interrupt source 17. The PC5 pin can serve as an external interrupt source for pin change interrupt 2.
60
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 10-11 and Table 10-12 relate the alternate functions of Port C to the overriding signals shown in Figure 10-6 on page 52. Table 10-11. Overriding Signals for Alternate Functions in PC[5:3]
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE PC5/CLKI/PCINT17 EXT_CLOCK 0 EXT_CLOCK(1) 0 EXT_CLOCK 0 0 EXT_CLOCK + (PCINT17 * PCIE2) (EXT_CLOCK * PWR_DOWN ) + (EXT_CLOCK(1) * PCINT17 * PCIE2) CLOCK / PCINT17 Input
(1) (1)
PC4/MOSI/SDA/PCINT16 0 0 (SPE * MSTR) + TWEN TWEN * SDA_OUT TWEN + (SPE * MSTR) TWEN * SPE * MSTR * SPI_MASTER_OUT + TWEN * (SPE + MSTR) 0 PCINT16 * PCIE2
PC3/RESET/PCINT15 RSTDISBL(2) 1 RSTDISBL(2) 0 RSTDISBL(2) 0 0 RSTDISBL(2) + (PCINT15 * PCIE2) RSTDISBL(2) * PCINT15 * PCIE2 PCINT15 Input
DIEOV DI AIO Notes:
PCINT16 * PCIE2 PCINT16 / SPI Slave Input SDA Input
1. EXT_CLOCK = external clock is selected as system clock. 2. x RSTDISBL is 1 when the configuration bit is "0" (programmed). 3. When TWI is enabled the slew rate control and spike filter are activated on PC4. This is not illustrated in Figure 10-6 on page 52. The spike filter is connected between AIOxn and the TWI.
61
8263A-AVR-08/10
Table 10-12. Overriding Signals for Alternate Functions in PC[2:0]
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO Notes: CKOUT PC2/INT0/CLKO/MISO/ PCINT14 CKOUT 0 CKOUT(1) + (SPE * MSTR) CKOUT
(1) (1)
PC1/SCK/SCL/ICP1/T1/ PCINT13 0 0 TWEN + (SPE * MSTR) TWEN + SCL_OUT TWEN + (SPE * MSTR) TWEN * (SPE * MSTR * SCK_OUT * (SPE + MSTR)) 0 PCINT13 * PCIE2 PCINT13 * PCIE2 ICP1 / SCK / T1 / SCL / PCINT13 Input SCL Input
PC0/OC0A/SS/PCINT12 0 0 SPE * MSTR 0 OC0A_ENABLE OC0A 0 PCINT12 * PCIE2 PCINT12 * PCIE2 SPI SS / PCINT12 Input
+ (SPE * MSTR)
CKOUT * System Clock + CKOUT * SPE * MSTR * SPI_SLAVE_OUT 0 (PCINT14 * PCIE2) + INT0 (PCINT14 * PCIE2) + INT0 INT0 / PCINT14 / SPI Master Input
(1)
1. CKOUT is 1 when the configuration bit is "0" (programmed). 2. When TWI is enabled the slew rate control and spike filter are activated on PC1. This is not illustrated in Figure 10-6 on page 52. The spike filter is connected between AIOxn and the TWI.
10.4
10.4.1
Register Description
PORTCR - Port Control Register
Bit 0x08 Read/Write Initial Value 7 ADC11D R/W 0 6 ADC10D R/W 0 5 ADC9D R/W 0 4 ADC8D R/W 0 3 - R 0 2 BBMC R/W 0 1 BBMB R/W 0 0 BBMA R/W 0 PORTCR
* Bit 3 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 2 - BBMC: Break-Before-Make Mode Enable When this bit is set the Break-Before-Make mode is activated for the entire Port C. The intermediate tri-state cycle is then inserted when writing DDRCn to make an output. For further information, see "Break-Before-Make Switching" on page 48 * Bit 1 - BBMB: Break-Before-Make Mode Enable When this bit is set the Break-Before-Make mode is activated for the entire Port B. The intermediate tri-state cycle is then inserted when writing DDRBn to make an output. For further information, see "Break-Before-Make Switching" on page 48.
62
ATtiny40
8263A-AVR-08/10
ATtiny40
* Bit 0 - BBMA: Break-Before-Make Mode Enable When this bit is set the Break-Before-Make mode is activated for the entire Port A. The intermediate tri-state cycle is then inserted when writing DDRAn to make an output. For further information, see "Break-Before-Make Switching" on page 48.
10.4.2
PUEA - Port A Pull-up Enable Control Register
Bit 0x03 Read/Write Initial Value 7 PUEA7 R/W 0 6 PUEA6 R/W 0 5 PUEA5 R/W 0 4 PUEA4 R/W 0 3 PUEA3 R/W 0 2 PUEA2 R/W 0 1 PUEA1 R/W 0 0 PUEA0 R/W 0 PUEA
10.4.3
PORTA - Port A Data Register
Bit 0x02 Read/Write Initial Value 7 PORTA7 R/W 0 6 PORTA6 R/W 0 5 PORTA5 R/W 0 4 PORTA4 R/W 0 3 PORTA3 R/W 0 2 PORTA2 R/W 0 1 PORTA1 R/W 0 0 PORTA0 R/W 0 PORTA
10.4.4
DDRA - Port A Data Direction Register
Bit 0x01 Read/Write Initial Value 7 DDA7 R/W 0 6 DDA6 R/W 0 5 DDA5 R/W 0 4 DDA4 R/W 0 3 DDA3 R/W 0 2 DDA2 R/W 0 1 DDA1 R/W 0 0 DDA0 R/W 0 DDRA
10.4.5
PINA - Port A Input Pins
Bit 0x00 Read/Write Initial Value 7 PINA7 R/W N/A 6 PINA6 R/W N/A 5 PINA5 R/W N/A 4 PINA4 R/W N/A 3 PINA3 R/W N/A 2 PINA2 R/W N/A 1 PINA1 R/W N/A 0 PINA0 R/W N/A PINA
10.4.6
PUEB - Port B Pull-up Enable Control Register
Bit 0x07 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 PUEB3 R/W 0 2 PUEB2 R/W 0 1 PUEB1 R/W 0 0 PUEB0 R/W 0 PUEB
10.4.7
PORTB - Port B Data Register
Bit 0x06 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 PORTB3 R/W 0 2 PORTB2 R/W 0 1 PORTB1 R/W 0 0 PORTB0 R/W 0 PORTB
10.4.8
DDRB - Port B Data Direction Register
Bit 0x05 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 DDB3 R/W 0 2 DDB2 R/W 0 1 DDB1 R/W 0 0 DDB0 R/W 0 DDRB
63
8263A-AVR-08/10
10.4.9
PINB - Port B Input Pins
Bit 0x04 Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 PINB3 R/W N/A 2 PINB2 R/W N/A 1 PINB1 R/W N/A 0 PINB0 R/W N/A PINB
10.4.10
PUEC - Port C Pull-up Enable Control Register
Bit 0x1E Read/Write Initial Value 7 - R 0 6 - R 0 5 PUEC5 R/W 0 4 PUEC4 R/W 0 3 PUEC3 R/W 0 2 PUEC2 R/W 0 1 PUEC1 R/W 0 0 PUEC0 R/W 0 PUEC
10.4.11
PORTC - Port C Data Register
Bit 0x1D Read/Write Initial Value 7 - R 0 6 - R 0 5 PORTC5 R/W 0 4 PORTC4 R/W 0 3 PORTC3 R/W 0 2 PORTC2 R/W 0 1 PORTC1 R/W 0 0 PORTC0 R/W 0 PORTC
10.4.12
DDRC - Port C Data Direction Register
Bit 0x1C Read/Write Initial Value 7 - R 0 6 - R 0 5 PINC5 R/W 0 4 PINC4 R/W 0 3 DDC3 R/W 0 2 DDC2 R/W 0 1 DDC1 R/W 0 0 DDC0 R/W 0 DDRC
10.4.13
PINC - Port C Input Pins
Bit 0x1B Read/Write Initial Value 7 - R 0 6 - R 0 5 PINC5 R/W 0 4 PINC4 R/W 0 3 PINC3 R/W N/A 2 PINC2 R/W N/A 1 PINC1 R/W N/A 0 PINC0 R/W N/A PINC
64
ATtiny40
8263A-AVR-08/10
ATtiny40
11. Timer/Counter0
11.1 Features
* * * * * * *
Two Independent Output Compare Units Double Buffered Output Compare Registers Clear Timer on Compare Match (Auto Reload) Glitch Free, Phase Correct Pulse Width Modulator (PWM) Variable PWM Period Frequency Generator Three Independent Interrupt Sources (TOV0, OCF0A, and OCF0B)
11.2
Overview
Timer/Counter0 is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and with PWM support. It allows accurate program execution timing (event management) and wave generation. A simplified block diagram of the 8-bit Timer/Counter is shown in Figure 11-1 on page 65. For the actual placement of I/O pins, refer to Figure 1-1 on page 2. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the "Register Description" on page 76. Figure 11-1. 8-bit Timer/Counter Block Diagram
Count Clear Direction Control Logic TOVn (Int.Req.) clkTn Clock Select Edge Detector TOP BOTTOM ( From Prescaler ) Timer/Counter TCNTn Tn
=
=0
OCnA (Int.Req.)
=
OCRnA Fixed TOP Value
Waveform Generation
OCnA
DATA BUS
OCnB (Int.Req.) Waveform Generation OCnB
=
OCRnB
TCCRnA
TCCRnB
65
8263A-AVR-08/10
11.2.1
Registers The Timer/Counter (TCNT0) and Output Compare Registers (OCR0A and OCR0B) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in Figure 11-1) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the T0 pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment (or decrement) its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkT0). The double buffered Output Compare Registers (OCR0A and OCR0B) is compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC0A and OC0B). See "Output Compare Unit" on page 67 for details. The Compare Match event will also set the Compare Flag (OCF0A or OCF0B) which can be used to generate an Output Compare interrupt request.
11.2.2
Definitions Many register and bit references in this section are written in general form. A lower case "n" replaces the Timer/Counter number, in this case 0. A lower case "x" replaces the Output Compare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0 for accessing Timer/Counter0 counter value and so on. The definitions in Table 11-1 are also used extensively throughout the document. Table 11-1.
Constant BOTTOM MAX TOP
Definitions
Description The counter reaches BOTTOM when it becomes 0x00 The counter reaches its MAXimum when it becomes 0xFF (decimal 255) The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR0A Register. The assignment depends on the mode of operation
11.3
Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS0[2:0]) bits located in the Timer/Counter Control Register (TCCR0B). For details on clock sources and prescaler, see "Timer/Counter Prescaler" on page 98.
11.4
Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 11-2 on page 67 shows a block diagram of the counter and its surroundings.
66
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 11-2. Counter Unit Block Diagram
DATA BUS
TOVn (Int.Req.)
Clock Select count TCNTn clear direction ( From Prescaler ) bottom top Control Logic clkTn Edge Detector Tn
Signal description (internal signals): count direction clear clkTn top bottom Increment or decrement TCNT0 by 1. Select between increment and decrement. Clear TCNT0 (set all bits to zero). Timer/Counter clock, referred to as clkT0 in the following. Signalize that TCNT0 has reached maximum value. Signalize that TCNT0 has reached minimum value (zero).
Depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS0[2:0]). When no clock source is selected (CS0[2:0] = 0) the timer is stopped. However, the TCNT0 value can be accessed by the CPU, regardless of whether clkT0 is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the Timer/Counter Control Register (TCCR0A) and the WGM02 bit located in the Timer/Counter Control Register B (TCCR0B). There are close connections between how the counter behaves (counts) and how waveforms are generated on the Output Compare output OC0A. For more details about advanced counting sequences and waveform generation, see "Modes of Operation" on page 70. The Timer/Counter Overflow Flag (TOV0) is set according to the mode of operation selected by the WGM0[1:0] bits. TOV0 can be used for generating a CPU interrupt.
11.5
Output Compare Unit
The 8-bit comparator continuously compares TCNT0 with the Output Compare Registers (OCR0A and OCR0B). Whenever TCNT0 equals OCR0A or OCR0B, the comparator signals a match. A match will set the Output Compare Flag (OCF0A or OCF0B) at the next timer clock cycle. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. The Waveform Generator uses the match signal to generate an output according to operating mode set by the WGM0[2:0] bits and Compare Output mode (COM0x[1:0]) bits. The max and bottom signals are used by the Waveform Generator for handling the special cases of the extreme values in some modes of operation. See "Modes of Operation" on page 70.
67
8263A-AVR-08/10
Figure 11-3 on page 68 shows a block diagram of the Output Compare unit. Figure 11-3. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8-bit Comparator )
OCFnx (Int.Req.)
top bottom FOCn
Waveform Generator
OCnx
WGMn1:0
COMnX1:0
The OCR0x Registers are double buffered when using any of the Pulse Width Modulation (PWM) modes. For the normal and Clear Timer on Compare (CTC) modes of operation, the double buffering is disabled. The double buffering synchronizes the update of the OCR0x Compare Registers to either top or bottom of the counting sequence. The synchronization prevents the occurrence of odd-length, non-symmetrical PWM pulses, thereby making the output glitch-free. The OCR0x Register access may seem complex, but this is not case. When the double buffering is enabled, the CPU has access to the OCR0x Buffer Register, and if double buffering is disabled the CPU will access the OCR0x directly. 11.5.1 Force Output Compare In non-PWM waveform generation modes, the match output of the comparator can be forced by writing a one to the Force Output Compare (0x) bit. Forcing Compare Match will not set the OCF0x Flag or reload/clear the timer, but the OC0x pin will be updated as if a real Compare Match had occurred (the COM0x[1:0] bits settings define whether the OC0x pin is set, cleared or toggled). Compare Match Blocking by TCNT0 Write All CPU write operations to the TCNT0 Register will block any Compare Match that occur in the next timer clock cycle, even when the timer is stopped. This feature allows OCR0x to be initialized to the same value as TCNT0 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT0 in any mode of operation will block all Compare Matches for one timer clock cycle, there are risks involved when changing TCNT0 when using the Output Compare Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNT0
11.5.2
11.5.3
68
ATtiny40
8263A-AVR-08/10
ATtiny40
equals the OCR0x value, the Compare Match will be missed, resulting in incorrect waveform generation. Similarly, do not write the TCNT0 value equal to BOTTOM when the counter is down-counting. The setup of the OC0x should be performed before setting the Data Direction Register for the port pin to output. The easiest way of setting the OC0x value is to use the Force Output Compare (0x) strobe bits in Normal mode. The OC0x Registers keep their values even when changing between Waveform Generation modes. Be aware that the COM0x[1:0] bits are not double buffered together with the compare value. Changing the COM0x[1:0] bits will take effect immediately.
11.6
Compare Match Output Unit
The Compare Output mode (COM0x[1:0]) bits have two functions. The Waveform Generator uses the COM0x[1:0] bits for defining the Output Compare (OC0x) state at the next Compare Match. Also, the COM0x[1:0] bits control the OC0x pin output source. Figure 11-4 on page 69 shows a simplified schematic of the logic affected by the COM0x[1:0] bit setting. The I/O Registers, I/O bits, and I/O pins in the figure are shown in bold. Only the parts of the general I/O Port Control Registers (DDR and PORT) that are affected by the COM0x[1:0] bits are shown. When referring to the OC0x state, the reference is for the internal OC0x Register, not the OC0x pin. If a system reset occur, the OC0x Register is reset to "0". Figure 11-4. Compare Match Output Unit, Schematic
COMnx1 COMnx0 FOCn
Waveform Generator
D
Q
1 OCn Pin
OCnx D Q
0
DATA BUS
PORT D Q
DDR
clk I/O
The general I/O port function is overridden by the Output Compare (OC0x) from the Waveform Generator if either of the COM0x[1:0] bits are set. However, the OC0x pin direction (input or output) is still controlled by the Data Direction Register (DDR) for the port pin. The Data Direction
69
8263A-AVR-08/10
Register bit for the OC0x pin (DDR_OC0x) must be set as output before the OC0x value is visible on the pin. The port override function is independent of the Waveform Generation mode. The design of the Output Compare pin logic allows initialization of the OC0x state before the output is enabled. Note that some COM0x[1:0] bit settings are reserved for certain modes of operation, see "Register Description" on page 76 11.6.1 Compare Output Mode and Waveform Generation The Waveform Generator uses the COM0x[1:0] bits differently in Normal, CTC, and PWM modes. For all modes, setting the COM0x[1:0] = 0 tells the Waveform Generator that no action on the OC0x Register is to be performed on the next Compare Match. For compare output actions in the non-PWM modes refer to Table 11-2 on page 76. For fast PWM mode, refer to Table 11-3 on page 77, and for phase correct PWM refer to Table 11-4 on page 77. A change of the COM0x[1:0] bits state will have effect at the first Compare Match after the bits are written. For non-PWM modes, the action can be forced to have immediate effect by using the 0x strobe bits.
11.7
Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is defined by the combination of the Waveform Generation mode (WGM0[2:0]) and Compare Output mode (COM0x[1:0]) bits. The Compare Output mode bits do not affect the counting sequence, while the Waveform Generation mode bits do. The COM0x[1:0] bits control whether the PWM output generated should be inverted or not (inverted or non-inverted PWM). For nonPWM modes the COM0x[1:0] bits control whether the output should be set, cleared, or toggled at a Compare Match (See "Modes of Operation" on page 70). For detailed timing information refer to Figure 11-8 on page 75, Figure 11-9 on page 75, Figure 11-10 on page 75 and Figure 11-11 on page 76 in "Timer/Counter Timing Diagrams" on page 74.
11.7.1
Normal Mode The simplest mode of operation is the Normal mode (WGM0[2:0] = 0). In this mode the counting direction is always up (incrementing), and no counter clear is performed. The counter simply overruns when it passes its maximum 8-bit value (TOP = 0xFF) and then restarts from the bottom (0x00). In normal operation the Timer/Counter Overflow Flag (TOV0) will be set in the same timer clock cycle as the TCNT0 becomes zero. The TOV0 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV0 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time. Using the Output Compare to generate waveforms in Normal mode is not recommended, since this will occupy too much of the CPU time.
11.7.2
Clear Timer on Compare Match (CTC) Mode In Clear Timer on Compare or CTC mode (WGM0[2:0] = 2), the OCR0A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence
70
ATtiny40
8263A-AVR-08/10
ATtiny40
also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events. The timing diagram for the CTC mode is shown in Figure 11-5 on page 71. The counter value (TCNT0) increases until a Compare Match occurs between TCNT0 and OCR0A, and then counter (TCNT0) is cleared. Figure 11-5. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
TCNTn Period
1 2 3 4
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR0A is lower than the current value of TCNT0, the counter will miss the Compare Match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur. For generating a waveform output in CTC mode, the OC0A output can be set to toggle its logical level on each Compare Match by setting the Compare Output mode bits to toggle mode (COM0A[1:0] = 1). The OC0A value will not be visible on the port pin unless the data direction for the pin is set to output. The waveform generated will have a maximum frequency of 0 = fclk_I/O/2 when OCR0A is set to zero (0x00). The waveform frequency is defined by the following equation: f clk_I/O f OCnx = ------------------------------------------------2 N ( 1 + OCRnx ) The N variable represents the prescale factor (1, 8, 64, 256, or 1024). As for the Normal mode of operation, the TOV0 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 11.7.3 Fast PWM Mode The fast Pulse Width Modulation or fast PWM mode (WGM0[2:0] = 3 or 7) provides a high frequency PWM waveform generation option. The fast PWM differs from the other PWM option by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM. TOP is defined as 0xFF when WGM0[2:0] = 3, and OCR0A when WGM0[2:0] = 7. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match between TCNT0 and OCR0x, and set at BOTTOM. In inverting Compare Output mode, the out-
71
8263A-AVR-08/10
put is set on Compare Match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct PWM mode that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. In fast PWM mode, the counter is incremented until the counter value matches the TOP value. The counter is then cleared at the following timer clock cycle. The timing diagram for the fast PWM mode is shown in Figure 11-6 on page 72. The TCNT0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. The diagram includes noninverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0x and TCNT0. Figure 11-6. Fast PWM Mode, Timing Diagram
OCRnx Interrupt Flag Set
OCRnx Update and TOVn Interrupt Flag Set
TCNTn
OCn OCn
(COMnx[1:0] = 2)
(COMnx[1:0] = 3)
Period
1
2
3
4
5
6
7
The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches TOP. If the interrupt is enabled, the interrupt handler routine can be used for updating the compare value. In fast PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x[1:0] bits to two will produce a non-inverted PWM and an inverted PWM output can be generated by setting the COM0x[1:0] to three: Setting the COM0A[1:0] bits to one allowes the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (See Table 11-3 on page 77). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by setting (or clearing) the OC0x Register at the Compare Match between OCR0x and TCNT0, and clearing (or setting) the OC0x Register at the timer clock cycle the counter is cleared (changes from TOP to BOTTOM). The PWM frequency for the output can be calculated by the following equation: f clk_I/O f OCnxPWM = ----------------N 256 The N variable represents the prescale factor (1, 8, 64, 256, or 1024).
72
ATtiny40
8263A-AVR-08/10
ATtiny40
The extreme values for the OCR0A Register represents special cases when generating a PWM waveform output in the fast PWM mode. If the OCR0A is set equal to BOTTOM, the output will be a narrow spike for each MAX+1 timer clock cycle. Setting the OCR0A equal to MAX will result in a constantly high or low output (depending on the polarity of the output set by the COM0A[1:0] bits.) A frequency (with 50% duty cycle) waveform output in fast PWM mode can be achieved by setting OC0x to toggle its logical level on each Compare Match (COM0x[1:0] = 1). The waveform generated will have a maximum frequency of 0 = fclk_I/O/2 when OCR0A is set to zero. This feature is similar to the OC0A toggle in CTC mode, except the double buffer feature of the Output Compare unit is enabled in the fast PWM mode. 11.7.4 Phase Correct PWM Mode The phase correct PWM mode (WGM0[2:0] = 1 or 5) provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode is based on a dual-slope operation. The counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. TOP is defined as 0xFF when WGM0[2:0] = 1, and OCR0A when WGM0[2:0] = 5. In noninverting Compare Output mode, the Output Compare (OC0x) is cleared on the Compare Match between TCNT0 and OCR0x while upcounting, and set on the Compare Match while downcounting. In inverting Output Compare mode, the operation is inverted. The dual-slope operation has lower maximum operation frequency than single slope operation. However, due to the symmetric feature of the dual-slope PWM modes, these modes are preferred for motor control applications. Figure 11-7. Phase Correct PWM Mode, Timing Diagram
OCnx Interrupt Flag Set
OCRnx Update
TOVn Interrupt Flag Set
TCNTn
OCn OCn
(COMnx[1:0] = 2)
(COMnx[1:0] = 3)
Period
1
2
3
In phase correct PWM mode the counter is incremented until the counter value matches TOP. When the counter reaches TOP, it changes the count direction. The TCNT0 value will be equal to TOP for one timer clock cycle. The timing diagram for the phase correct PWM mode is shown on Figure 11-7. The TCNT0 value is in the timing diagram shown as a histogram for illustrating 73
8263A-AVR-08/10
the dual-slope operation. The diagram includes non-inverted and inverted PWM outputs. The small horizontal line marks on the TCNT0 slopes represent Compare Matches between OCR0x and TCNT0. The Timer/Counter Overflow Flag (TOV0) is set each time the counter reaches BOTTOM. The Interrupt Flag can be used to generate an interrupt each time the counter reaches the BOTTOM value. In phase correct PWM mode, the compare unit allows generation of PWM waveforms on the OC0x pins. Setting the COM0x[1:0] bits to two will produce a non-inverted PWM. An inverted PWM output can be generated by setting the COM0x[1:0] to three: Setting the COM0A0 bits to one allows the OC0A pin to toggle on Compare Matches if the WGM02 bit is set. This option is not available for the OC0B pin (See Table 11-4 on page 77). The actual OC0x value will only be visible on the port pin if the data direction for the port pin is set as output. The PWM waveform is generated by clearing (or setting) the OC0x Register at the Compare Match between OCR0x and TCNT0 when the counter increments, and setting (or clearing) the OC0x Register at Compare Match between OCR0x and TCNT0 when the counter decrements. The PWM frequency for the output when using phase correct PWM can be calculated by the following equation: f clk_I/O f OCnxPCPWM = ----------------N 510 The N variable represents the prescale factor (1, 8, 64, 256, or 1024). The extreme values for the OCR0A Register represent special cases when generating a PWM waveform output in the phase correct PWM mode. If the OCR0A is set equal to BOTTOM, the output will be continuously low and if set equal to MAX the output will be continuously high for non-inverted PWM mode. For inverted PWM the output will have the opposite logic values. At the very start of period 2 in Figure 11-7 on page 73 OCn has a transition from high to low even though there is no Compare Match. The point of this transition is to guaratee symmetry around BOTTOM. There are two cases that give a transition without Compare Match. * OCR0A changes its value from MAX, like in Figure 11-7 on page 73. When the OCR0A value is MAX the OCn pin value is the same as the result of a down-counting Compare Match. To ensure symmetry around BOTTOM the OCn value at MAX must correspond to the result of an up-counting Compare Match. * The timer starts counting from a value higher than the one in OCR0A, and for that reason misses the Compare Match and hence the OCn change that would have happened on the way up.
11.8
Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT0) is therefore shown as a clock enable signal in the following figures. The figures include information on when Interrupt Flags are set. Figure 11-8 on page 75 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value in all modes other than phase correct PWM mode.
74
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 11-8. Timer/Counter Timing Diagram, no Prescaling
clkI/O clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 11-9 on page 75 shows the same timing data, but with the prescaler enabled. Figure 11-9. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 11-10 on page 75 shows the setting of OCF0B in all modes and OCF0A in all modes except CTC mode and PWM mode, where OCR0A is TOP. Figure 11-10. Timer/Counter Timing Diagram, Setting of OCF0x, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx
OCRnx Value
OCFnx
Figure 11-11 on page 76 shows the setting of OCF0A and the clearing of TCNT0 in CTC mode and fast PWM mode where OCR0A is TOP.
75
8263A-AVR-08/10
Figure 11-11. Timer/Counter Timing Diagram, Clear Timer on Compare Match mode, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn (CTC) OCRnx
TOP - 1
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
11.9
11.9.1
Register Description
TCCR0A - Timer/Counter Control Register A
Bit 0x19 Read/Write Initial Value 7 COM0A1 R/W 0 6 COM0A0 R/W 0 5 COM0B1 R/W 0 4 COM0B0 R/W 0 3 - R 0 2 - R 0 1 WGM01 R/W 0 0 WGM00 R/W 0 TCCR0A
* Bits 7:6 - COM0A[1:0]: Compare Match Output A Mode These bits control the Output Compare pin (OC0A) behavior. If one or both of the COM0A[1:0] bits are set, the OC0A output overrides the normal port functionality of the I/O pin it is connected to. However, note that the Data Direction Register (DDR) bit corresponding to the OC0A pin must be set in order to enable the output driver. When OC0A is connected to the pin, the function of the COM0A[1:0] bits depends on the WGM0[2:0] bit setting. Table 11-2 shows the COM0A[1:0] bit functionality when the WGM0[2:0] bits are set to a normal or CTC mode (non-PWM). Table 11-2.
COM0A1 0 0 1 1
Compare Output Mode, non-PWM Mode
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. Toggle OC0A on Compare Match Clear OC0A on Compare Match Set OC0A on Compare Match
Table 11-3 shows COM0A[1:0] bit functionality when WGM0[1:0] bits are set to fast PWM mode.
76
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 11-3.
COM0A1 0 0 1 1 Note:
Compare Output Mode, Fast PWM Mode(1)
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected WGM02 = 0: Normal Port Operation, OC0A Disconnected WGM02 = 1: Toggle OC0A on Compare Match Clear OC0A on Compare Match Set OC0A at BOTTOM (non-inverting mode) Set OC0A on Compare Match Clear OC0A at BOTTOM (inverting mode)
1. A special case occurs when OCR0A equals TOP and COM0A1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 71 for more details.
Table 11-4 shows COM0A[1:0] bit functionality when WGM0[2:0] bits are set to phase correct PWM mode. Table 11-4.
COM0A1 0 0 1 1 Note:
Compare Output Mode, Phase Correct PWM Mode(1)
COM0A0 0 1 0 1 Description Normal port operation, OC0A disconnected. WGM02 = 0: Normal Port Operation, OC0A Disconnected. WGM02 = 1: Toggle OC0A on Compare Match. Clear OC0A on Compare Match when up-counting. Set OC0A on Compare Match when down-counting. Set OC0A on Compare Match when up-counting. Clear OC0A on Compare Match when down-counting.
1. When OCR0A equals TOP and COM0A1 is set, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 73 for more details.
* Bits 5:4 - COM0B[1:0]: Compare Match Output B Mode These bits control the Output Compare pin (OC0B) behavior. If one or both of COM0B[1:0] bits are set, the OC0B output overrides the normal port functionality of the I/O pin it is connected to. The Data Direction Register (DDR) bit corresponding to the OC0B pin must be set in order to enable the output driver. When OC0B is connected to the pin, the function of COM0B[1:0] bits depend on WGM0[2:0] bit setting. Table 11-5 shows COM0B[1:0] bit functionality when WGM0[2:0] bits are set to normal or CTC mode (non-PWM). Table 11-5.
COM0B1 0 0 1 1
Compare Output Mode, non-PWM Mode
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Toggle OC0B on Compare Match Clear OC0B on Compare Match Set OC0B on Compare Match
77
8263A-AVR-08/10
Table 11-6 shows COM0B[1:0] bit functionality when WGM0[2:0] bits are set to fast PWM mode. Table 11-6.
COM0B1 0 0 1 1 Note:
Compare Output Mode, Fast PWM Mode(1)
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match, set OC0B at BOTTOM (non-inverting mode) Set OC0B on Compare Match, clear OC0B at BOTTOM (inverting mode)
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at BOTTOM. See "Fast PWM Mode" on page 71 for more details.
Table 11-7 shows the COM0B[1:0] bit functionality when the WGM0[2:0] bits are set to phase correct PWM mode. Table 11-7.
COM0B1 0 0 1 1 Note:
Compare Output Mode, Phase Correct PWM Mode(1)
COM0B0 0 1 0 1 Description Normal port operation, OC0B disconnected. Reserved Clear OC0B on Compare Match when up-counting. Set OC0B on Compare Match when down-counting. Set OC0B on Compare Match when up-counting. Clear OC0B on Compare Match when down-counting.
1. A special case occurs when OCR0B equals TOP and COM0B1 is set. In this case, the Compare Match is ignored, but the set or clear is done at TOP. See "Phase Correct PWM Mode" on page 73 for more details.
* Bits 3:2 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 1:0 - WGM0[1:0]: Waveform Generation Mode Combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used, see Table 11-8. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) mode, and two types of Pulse Width Modulation (PWM) modes (see "Modes of Operation" on page 70).
78
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 11-8.
Mode 0 1 2 3 4 5 6 7 Note:
Waveform Generation Mode Bit Description
WGM02 0 0 0 0 1 1 1 1 WGM01 0 0 1 1 0 0 1 1 WGM00 0 1 0 1 0 1 0 1 Timer/Counter Mode of Operation Normal PWM, Phase Correct CTC Fast PWM Reserved PWM, Phase Correct Reserved Fast PWM TOP 0xFF 0xFF OCRA 0xFF - OCRA - OCRA Update of OCRx at Immediate TOP Immediate BOTTOM - TOP - BOTTOM TOV Flag Set on(1) MAX BOTTOM MAX MAX - BOTTOM - TOP
1. MAX = 0xFF BOTTOM = 0x00
11.9.2
TCCR0B - Timer/Counter Control Register B
Bit 0x18 Read/Write Initial Value 7 FOC0A W 0 6 FOC0B W 0 5 TSM R/W 0 4 PSR R/W 0 3 WGM02 R/W 0 2 CS02 R/W 0 1 CS01 R/W 0 0 CS00 R/W 0 TCCR0B
* Bit 7 - FOC0A: Force Output Compare A The FOC0A bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0A bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0A output is changed according to its COM0A[1:0] bits setting. Note that the FOC0A bit is implemented as a strobe. Therefore it is the value present in the COM0A[1:0] bits that determines the effect of the forced compare. A FOC0A strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0A as TOP. The FOC0A bit always reads as zero. * Bit 6 - FOC0B: Force Output Compare B The FOC0B bit is only active when the WGM bits specify a non-PWM mode. However, for ensuring compatibility with future devices, this bit must be set to zero when TCCR0B is written when operating in PWM mode. When writing a logical one to the FOC0B bit, an immediate Compare Match is forced on the Waveform Generation unit. The OC0B output is changed according to its COM0B[1:0] bits setting. Note that the FOC0B bit is implemented as a strobe. Therefore it is the value present in the COM0B[1:0] bits that determines the effect of the forced compare.
79
8263A-AVR-08/10
A FOC0B strobe will not generate any interrupt, nor will it clear the timer in CTC mode using OCR0B as TOP. The FOC0B bit always reads as zero. * Bit 3 - WGM02: Waveform Generation Mode See the description in the "TCCR0A - Timer/Counter Control Register A" on page 76. * Bits 2:0 - CS0[2:0]: Clock Select The three Clock Select bits select the clock source to be used by the Timer/Counter. Table 11-9.
CS02 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1
Clock Select Bit Description
CS00 0 1 0 1 0 1 0 1 Description No clock source (Timer/Counter stopped) clkI/O/(No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on T0 pin. Clock on falling edge. External clock source on T0 pin. Clock on rising edge.
CS01
If external pin modes are used for the Timer/Counter0, transitions on the T0 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 11.9.3 TCNT0 - Timer/Counter Register
Bit 0x17 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 TCNT0 R/W 0 TCNT0[7:0]
The Timer/Counter Register gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT0 Register blocks (removes) the Compare Match on the following timer clock. Modifying the counter (TCNT0) while the counter is running, introduces a risk of missing a Compare Match between TCNT0 and the OCR0x Registers. 11.9.4 OCR0A - Output Compare Register A
Bit 0x16 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR0A R/W 0 OCR0A[7:0]
The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0A pin.
80
ATtiny40
8263A-AVR-08/10
ATtiny40
11.9.5 OCR0B - Output Compare Register B
Bit 0x15 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR0B R/W 0 OCR0B[7:0]
The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNT0). A match can be used to generate an Output Compare interrupt, or to generate a waveform output on the OC0B pin. 11.9.6 TIMSK - Timer/Counter Interrupt Mask Register
Bit 0x26 Read/Write Initial Value 7 ICIE1 R/W 0 6 - R 0 5 OCIE1B R/W 0 4 OCIE1A R/W 0 3 TOIE1 R/W 0 2 OCIE0B R/W 0 1 OCIE0A R/W 0 0 TOIE0 R/W 0 TIMSK
* Bit 6 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 2 - OCIE0B: Timer/Counter Output Compare Match B Interrupt Enable When the OCIE0B bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter Compare Match B interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter occurs, i.e., when the OCF0B bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 1 - OCIE0A: Timer/Counter0 Output Compare Match A Interrupt Enable When the OCIE0A bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter0 Compare Match A interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter0 occurs, i.e., when the OCF0A bit is set in the Timer/Counter Interrupt Flag Register - TIFR. * Bit 0 - TOIE0: Timer/Counter0 Overflow Interrupt Enable When the TOIE0 bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter0 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter0 occurs, i.e., when the TOV0 bit is set in the Timer/Counter Interrupt Flag Register - TIFR. 11.9.7 TIFR - Timer/Counter Interrupt Flag Register
Bit 0x25 Read/Write Initial Value 7 ICF1 R/W 0 6 - R 0 5 OCF1B R/W 0 4 OCF1A R/W 0 3 TOV1 R/W 0 2 OCF0B R/W 0 1 OCF0A R/W 0 0 TOV0 R/W 0 TIFR
* Bit 6 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 2 - OCF0B: Output Compare Flag 0 B The OCF0B bit is set when a Compare Match occurs between the Timer/Counter and the data in OCR0B - Output Compare Register0 B. OCF0B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0B is cleared by writing a logic one to
81
8263A-AVR-08/10
the flag. When the I-bit in SREG, OCIE0B (Timer/Counter Compare B Match Interrupt Enable), and OCF0B are set, the Timer/Counter Compare Match Interrupt is executed. * Bit 1 - OCF0A: Output Compare Flag 0 A The OCF0A bit is set when a Compare Match occurs between the Timer/Counter0 and the data in OCR0A - Output Compare Register0. OCF0A is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE0A (Timer/Counter0 Compare Match Interrupt Enable), and OCF0A are set, the Timer/Counter0 Compare Match Interrupt is executed. * Bit 0 - TOV0: Timer/Counter0 Overflow Flag The bit TOV0 is set when an overflow occurs in Timer/Counter0. TOV0 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV0 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE0 (Timer/Counter0 Overflow Interrupt Enable), and TOV0 are set, the Timer/Counter0 Overflow interrupt is executed. The setting of this flag is dependent of the WGM0[2:0] bit setting. See Table 11-8 on page 79 and "Waveform Generation Mode Bit Description" on page 79.
82
ATtiny40
8263A-AVR-08/10
ATtiny40
12. Timer/Counter1
12.1 Features
* * * * *
Clear Timer on Compare Match (Auto Reload) One Input Capture unit Four Independent Interrupt Sources (TOV1, OCF1A, OCF1B, ICF1) 8-bit Mode with Two Independent Output Compare Units 16-bit Mode with One Independent Output Compare Unit
12.2
Overview
Timer/Counter1 is a general purpose 8/16-bit Timer/Counter module, with two/one Output Compare units and Input Capture feature. The general operation of Timer/Counter1 is described in 8/16-bit mode. A simplified block diagram of the 8/16-bit Timer/Counter is shown in Figure 12-1. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. For actual placement of I/O pins, refer to "Pin Description" on page 2. Device-specific I/O Register and bit locations are listed in the "Register Description" on page 94. Figure 12-1. 8/16-bit Timer/Counter Block Diagram
TOVn (Int. Req.)
Count Clear Direction
clk Tn Control Logic Clock Select Edge Detector ( From Prescaler ) Timer/Counter TCNTnH TCNTnL TOP Tn
=
Fixed TOP value OCnA (Int. Req.) OCnB (Int. Req.)
=
=
DATA BUS
ICFn (Int. Req.) OCRnB OCRnA
TCCRnA
Edge Detector
Noise Canceler
ICPn
12.2.1
Registers The Timer/Counter1 Low Byte Register (TCNT1L) and Output Compare Registers (OCR1A and OCR1B) are 8-bit registers. Interrupt request (abbreviated Int.Req. in Figure 12-1) signals are all
83
8263A-AVR-08/10
visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure. In 16-bit mode one more 8-bit register is available, the Timer/Counter1 High Byte Register (TCNT1H). Also, in 16-bit mode, there is only one output compare unit as the two Output Compare Registers, OCR1A and OCR1B, are combined to one, 16-bit Output Compare Register, where OCR1A contains the low byte and OCR1B contains the high byte of the word. When accessing 16-bit registers, special procedures described in section "Accessing Registers in 16bit Mode" on page 90 must be followed. 12.2.2 Definitions Many register and bit references in this section are written in general form. A lower case "n" replaces the Timer/Counter number, in this case 1. A lower case "x" replaces the Output Compare Unit, in this case Compare Unit A or Compare Unit B. However, when using the register or bit defines in a program, the precise form must be used, i.e. TCNT1L for accessing Timer/Counter1 counter value, and so on. The definitions in Table 11-1 are also used extensively throughout the document. Table 12-1.
Constant BOTTOM MAX TOP
Definitions
Description The counter reaches BOTTOM when it becomes 0x00 The counter reaches its MAXimum when it becomes 0xFF (decimal 255) The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF (MAX) or the value stored in the OCR1A Register. The assignment depends on the mode of operation
12.3
Clock Sources
The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select (CS1[2:0]) bits located in the Timer/Counter Control Register (TCCR1A). For details on clock sources and prescaler, see "Timer/Counter Prescaler" on page 98.
12.4
Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 12-2 shows a block diagram of the counter and its surroundings. Table 12-2. Counter Unit Block Diagram
TOVn (Int.Req.) Clock Select Edge Detector Tn
DATA BUS
TCNTn
count
Control Logic
clkTn
( From Prescaler ) top
84
ATtiny40
8263A-AVR-08/10
ATtiny40
Signal description (internal signals): count clkTn top Increment or decrement TCNT1 by 1. Timer/Counter clock, referred to as clkT1 in the following. Signalize that TCNT1 has reached maximum value.
The counter is incremented at each timer clock (clkT1) until it passes its TOP value and then restarts from BOTTOM. The counting sequence is determined by the setting of the CTC1 bit located in the Timer/Counter Control Register (TCCR1A). For more details about counting sequences, see "Modes of Operation" on page 87. clkT1 can be generated from an external or internal clock source, selected by the Clock Select bits (CS1[2:0]). When no clock source is selected (CS1[2:0] = 0) the timer is stopped. However, the TCNT1 value can be accessed by the CPU, regardless of whether clkT1 is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The Timer/Counter Overflow Flag (TOV1) is set when the counter reaches the maximum value and it can be used for generating a CPU interrupt.
12.5
Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give them a time-stamp indicating time of occurrence. The external signal indicating an event, or multiple events, can be applied via the ICP1 pin or alternatively, via the analog-comparator unit. The time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. Alternatively the time-stamps can be used for creating a log of the events. The Input Capture unit is illustrated by the block diagram shown in Figure 12-2. The elements of the block diagram that are not directly a part of the Input Capture unit are gray shaded. Figure 12-2. Input Capture Unit Block Diagram
DATA BUS
(8-bit)
TEMP (8-bit)
OCR0B (8-bit) WRITE
OCR0A (8-bit)
TCNT0H (8-bit)
TCNT0L (8-bit)
ICR0 (16-bit Register)
TCNT0 (16-bit Counter)
ICNC0
ICES0
ICP0
Noise Canceler
Edge Detector
ICF0 (Int.Req.)
The Output Compare Register OCR1A is a dual-purpose register that is also used as an 8-bit Input Capture Register ICR1. In 16-bit Input Capture mode the Output Compare Register 85
8263A-AVR-08/10
OCR1B serves as the high byte of the Input Capture Register ICR1. In 8-bit Input Capture mode the Output Compare Register OCR1B is free to be used as a normal Output Compare Register, but in 16-bit Input Capture mode the Output Compare Unit cannot be used as there are no free Output Compare Register(s). Even though the Input Capture register is called ICR1 in this section, it is refering to the Output Compare Register(s). When a change of the logic level (an event) occurs on the Input Capture pin (ICP1), and this change confirms to the setting of the edge detector, a capture will be triggered. When a capture is triggered, the value of the counter (TCNT1) is written to the Input Capture Register (ICR1). The Input Capture Flag (ICF1) is set at the same system clock as the TCNT1 value is copied into Input Capture Register. If enabled (ICIE1=1), the Input Capture Flag generates an Input Capture interrupt. The ICF1 flag is automatically cleared when the interrupt is executed. Alternatively the ICF1 flag can be cleared by software by writing a logical one to its I/O bit location. 12.5.1 Input Capture Trigger Source The trigger source for the Input Capture unit is the Input Capture pin (ICP1). The Input Capture pin (ICP1) input is sampled using the same technique as for the T1 pin (Figure 12-4 on page 94). The edge detector is also identical. However, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. An Input Capture can also be triggered by software by controlling the port of the ICP1 pin. 12.5.2 Noise Canceler The noise canceler improves noise immunity by using a simple digital filtering scheme. The noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNC1) bit in Timer/Counter Control Register A (TCCR1A). When enabled the noise canceler introduces additional four system clock cycles of delay from a change applied to the input, to the update of the ICR1 Register. The noise canceler uses the system clock and is therefore not affected by the prescaler. 12.5.3 Using the Input Capture Unit The main challenge when using the Input Capture unit is to assign enough processor capacity for handling the incoming events. The time between two events is critical. If the processor has not read the captured value in the ICR1 Register before the next event occurs, the ICR1 will be overwritten with a new value. In this case the result of the capture will be incorrect. When using the Input Capture interrupt, the ICR1 Register should be read as early in the interrupt handler routine as possible. The maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. Measurement of an external signal's duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the ICR1 Register has been read. After a change of the edge, the Input Capture Flag (ICF1) must be cleared by software (writing a logical one to the I/O bit location). For measuring frequency only, the trigger edge change is not required (if an interrupt handler is used).
86
ATtiny40
8263A-AVR-08/10
ATtiny40
12.6 Output Compare Unit
The comparator continuously compares Timer/Counter (TCNT1) with the Output Compare Registers (OCR1A and OCR1B), and whenever the Timer/Counter equals to the Output Compare Regisers, the comparator signals a match. A match will set the Output Compare Flag at the next timer clock cycle. In 8-bit mode the match can set either the Output Compare Flag OCF1A or OCF1B, but in 16-bit mode the match can set only the Output Compare Flag OCF1A as there is only one Output Compare Unit. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. Figure 12-3 shows a block diagram of the Output Compare unit. Figure 12-3. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8/16-bit Comparator )
OCFnx (Int.Req.)
12.6.1
Compare Match Blocking by TCNT1 Write All CPU write operations to the TCNT1H/L Register will block any Compare Match that occur in the next timer clock cycle, even when the timer is stopped. This feature allows OCR1A/B to be initialized to the same value as TCNT1 without triggering an interrupt when the Timer/Counter clock is enabled. Using the Output Compare Unit Since writing TCNT1H/L will block all Compare Matches for one timer clock cycle, there are risks involved when changing TCNT1H/L when using the Output Compare Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNT1H/L equals the OCR1A/B value, the Compare Match will be missed.
12.6.2
12.7
Modes of Operation
The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is defined by the Timer/Counter Width (TCW1), Input Capture Enable (ICEN1) and CTC Mode (CTC1) bits. See "TCCR1A - Timer/Counter1 Control Register A" on page 94.
87
8263A-AVR-08/10
Table 12-3 summarises the different modes of operation. Table 12-3.
Mode 0 1 2 3 4
Modes of operation
ICEN1 0 0 0 1 1 TCW1 0 0 1 0 1 CTC1 0 1 X X X Mode of Operation Normal, 8-bit Mode CTC Mode, 8-bit Normal, 16-bit Mode Input Capture Mode, 8-bit Input Capture Mode, 16-bit TOP 0xFF OCR0A 0xFFFF 0xFF 0xFFFF Update of OCRx at Immediate Immediate Immediate Immediate Immediate TOV Flag Set on MAX (0xFF) MAX (0xFF) MAX (0xFFFF) MAX (0xFF) MAX (0xFFFF)
12.7.1
Normal, 8-bit Mode In Normal 8-bit mode (see Table 12-3), the counter (TCNT1L) is incrementing until it overruns when it passes its maximum 8-bit value (MAX = 0xFF) and then restarts from the bottom (0x00). The Overflow Flag (TOV1) is set in the same timer clock cycle as when TCNT1L becomes zero. The TOV1 Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal 8-bit mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time. Clear Timer on Compare Match (CTC) 8-bit Mode In Clear Timer on Compare or CTC mode, see Table 12-3 on page 88, the OCR1A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT1) matches the OCR1A. The OCR1A defines the top value for the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events. The timing diagram for the CTC mode is shown in Figure 12-4. The counter value (TCNT1) increases until a Compare Match occurs between TCNT1 and OCR1A, and then counter (TCNT1) is cleared. Figure 12-4. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
12.7.2
TCNTn Period
1 2 3 4
An interrupt can be generated each time the counter value reaches the TOP value by using the OCF1A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCR1A is lower than the current value of TCNT1, the counter will miss the Compare Match. The counter will then have to count to
88
ATtiny40
8263A-AVR-08/10
ATtiny40
its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur. As for the Normal mode of operation, the TOV1 Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 12.7.3 Normal, 16-bit Mode In 16-bit mode, see Table 12-3 on page 88, the counter (TCNT1H/L) is a incrementing until it overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the bottom (0x0000). The Overflow Flag (TOV1) will be set in the same timer clock cycle as the TCNT1H/L becomes zero. The TOV1 Flag in this case behaves like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV1 Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time. 8-bit Input Capture Mode The Timer/Counter1 can also be used in an 8-bit Input Capture mode, see Table 12-3 on page 88 for bit settings. For full description, see the section "Input Capture Unit" on page 85. 16-bit Input Capture Mode The Timer/Counter1 can also be used in a 16-bit Input Capture mode, see Table 12-3 on page 88 for bit settings. For full description, see the section "Input Capture Unit" on page 85.
12.7.4
12.7.5
12.8
Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkT1) is therefore shown as a clock enable signal in the following figures. The figures include information on when Interrupt Flags are set. Figure 12-5 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value. Figure 12-5. Timer/Counter Timing Diagram, no Prescaling
clkI/O clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 12-6 shows the same timing data, but with the prescaler enabled.
89
8263A-AVR-08/10
Figure 12-6. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 12-7 on page 90 shows the setting of OCF1A and OCF1B in Normal mode. Figure 12-7. Timer/Counter Timing Diagram, Setting of OCF1x, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx
OCRnx Value
OCFnx
Figure 12-8 shows the setting of OCF1A and the clearing of TCNT1 in CTC mode. Figure 12-8. Timer/Counter Timing Diagram, CTC mode, with Prescaler (fclk_I/O/8)
clkPCK clkTn
(clkPCK /8)
TCNTn (CTC) OCRnx
TOP - 1
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
12.9
Accessing Registers in 16-bit Mode
In 16-bit mode (the TCW1 bit is set to one) the TCNT1H/L and OCR1A/B or TCNT1L/H and OCR1B/A are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. The 16-bit Timer/Counter has a single 8-bit register for temporary storing of the high byte of the 16-bit
90
ATtiny40
8263A-AVR-08/10
ATtiny40
access. The same temporary register is shared between all 16-bit registers. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written by the CPU, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. There is one exception in the temporary register usage. In the Output Compare mode the 16-bit Output Compare Register OCR1A/B is read without the temporary register, because the Output Compare Register contains a fixed value that is only changed by CPU access. However, in 16bit Input Capture mode the ICR1 register formed by the OCR1A and OCR1B registers must be accessed with the temporary register. To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low byte must be read before the high byte. The following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCR1A/B registers.
Assembly Code Example ... ; Set TCNT1 to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNT1H,r17 out TCNT1L,r16 ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ... C Code Example unsigned int i; ... /* Set TCNT1 to 0x01FF */ TCNT1H = 0x01; TCNT1L = 0xff; /* Read TCNT1 into i */ i = TCNT1L; i |= ((unsigned int)TCNT1H << 8); ... Note: See "Code Examples" on page 6.
The assembly code example returns the TCNT1H/L value in the r17:r16 register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer registers, 91
8263A-AVR-08/10
then the result of the access outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. The following code examples show how to do an atomic read of the TCNT1 register contents. Reading any of the OCR1 register can be done by using the same principle.
Assembly Code Example TIM1_ReadTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNT1 into r17:r16 in r16,TCNT1L in r17,TCNT1H ; Restore global interrupt flag out SREG,r18 ret C Code Example unsigned int TIM1_ReadTCNT1( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNT1 into i */ i = TCNT1L; i |= ((unsigned int)TCNT1H << 8); /* Restore global interrupt flag */ SREG = sreg; return i; } Note: See "Code Examples" on page 6.
The assembly code example returns the TCNT1H/L value in the r17:r16 register pair.
92
ATtiny40
8263A-AVR-08/10
ATtiny40
The following code examples show how to do an atomic write of the TCNT1H/L register contents. Writing any of the OCR1A/B registers can be done by using the same principle.
Assembly Code Example TIM1_WriteTCNT1: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNT1 to r17:r16 out TCNT1H,r17 out TCNT1L,r16 ; Restore global interrupt flag out SREG,r18 ret
C Code Example void TIM1_WriteTCNT1( unsigned int i ) { unsigned char sreg; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNT1 to i */ TCNT1H = (i >> 8); TCNT1L = (unsigned char)i; /* Restore global interrupt flag */ SREG = sreg; } Note: See "Code Examples" on page 6.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNT1H/L. 12.9.1 Reusing the temporary high byte register If writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. However, note that the same rule of atomic operation described previously also applies in this case.
93
8263A-AVR-08/10
12.10 Register Description
12.10.1 TCCR1A - Timer/Counter1 Control Register A
Bit 0x24 Read/Write Initial Value 7 TCW1 R/W 0 6 ICEN1 R/W 0 5 ICNC1 R/W 0 4 ICES1 R/W 0 3 CTC1 R/W 0 2 CS12 R/W 0 1 CS11 R/W 0 0 CS10 R/W 0 TCCR1A
* Bit 7 - TCW1: Timer/Counter1 Width When this bit is written to one, 16-bit mode is selected as described Figure 12-5 on page 89. Timer/Counter1 width is set to 16-bits and the Output Compare Registers OCR1A and OCR1B are combined to form one 16-bit Output Compare Register. Because the 16-bit registers TCNT1H/L and OCR1B/A are accessed by the AVR CPU via the 8-bit data bus, special procedures must be followed. These procedures are described in section "Accessing Registers in 16bit Mode" on page 90. * Bit 6 - ICEN1: Input Capture Mode Enable When this bit is written to one, the Input Capture Mode is enabled. * Bit 5 - ICNC1: Input Capture Noise Canceler Setting this bit activates the Input Capture Noise Canceler. When the noise canceler is activated, the input from the Input Capture Pin (ICP1) is filtered. The filter function requires four successive equal valued samples of the ICP1 pin for changing its output. The Input Capture is therefore delayed by four System Clock cycles when the noise canceler is enabled. * Bit 4 - ICES1: Input Capture Edge Select This bit selects which edge on the Input Capture Pin (ICP1) that is used to trigger a capture event. When the ICES1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ICES1 bit is written to one, a rising (positive) edge will trigger the capture. When a capture is triggered according to the ICES1 setting, the counter value is copied into the Input Capture Register. The event will also set the Input Capture Flag (ICF1), and this can be used to cause an Input Capture Interrupt, if this interrupt is enabled. * Bit 3 - CTC1: Waveform Generation Mode This bit controls the counting sequence of the counter, the source for maximum (TOP) counter value, see Figure 12-5 on page 89. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter) and Clear Timer on Compare Match (CTC) mode (see "Modes of Operation" on page 87). * Bits 2:0 - CS1[2:0]: Clock Select1, Bits 2, 1, and 0 The Clock Select1 bits 2, 1, and 0 define the prescaling source of Timer1. Table 12-4.
CS12 0 0 0 0
Clock Select Bit Description
CS11 0 0 1 1 CS10 0 1 0 1 Description No clock source (Timer/Counter stopped) clkI/O/(No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler)
94
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 12-4.
CS12 1 1 1 1
Clock Select Bit Description
CS11 0 0 1 1 CS10 0 1 0 1 Description clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on T1 pin. Clock on falling edge. External clock source on T1 pin. Clock on rising edge.
If external pin modes are used for the Timer/Counter1, transitions on the T1 pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 12.10.2 TCNT1L - Timer/Counter1 Register Low Byte
Bit 0x23 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 TCNT1L R/W 0 TCNT1L[7:0]
The Timer/Counter1 Register Low Byte, TCNT1L, gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNT1L Register blocks (disables) the Compare Match on the following timer clock. Modifying the counter (TCNT1L) while the counter is running, introduces a risk of missing a Compare Match between TCNT1L and the OCR1x Registers. In 16-bit mode the TCNT1L register contains the lower part of the 16-bit Timer/Counter1 Register. 12.10.3 TCNT1H - Timer/Counter1 Register High Byte
Bit 0x27 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 TCNT1H R/W 0 TCNT1H[7:0]
When 16-bit mode is selected (the TCW1 bit is set to one) the Timer/Counter Register TCNT1H combined to the Timer/Counter Register TCNT1L gives direct access, both for read and write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90 12.10.4 OCR1A - Timer/Counter1 Output Compare Register A
Bit 0x22 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR1A R/W 0 OCR1A[7:0]
The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNT1L). A match can be used to generate an Output Compare interrupt. In 16-bit mode the OCR1A register contains the low byte of the 16-bit Output Compare Register. To ensure that both the high and the low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90. 95
8263A-AVR-08/10
12.10.5
OCR1B - Timer/Counter1 Output Compare Register B
Bit 0x21 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0 OCR1B R/W 0 OCR1B[7:0]
The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNT1L in 8-bit mode and TCNTH in 16-bit mode). A match can be used to generate an Output Compare interrupt. In 16-bit mode the OCR1B register contains the high byte of the 16-bit Output Compare Register. To ensure that both the high and the low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90. 12.10.6 TIMSK - Timer/Counter1 Interrupt Mask Register
Bit 0x26 Read/Write Initial Value 7 ICIE1 R/W 0 6 - R 0 5 OCIE1B R/W 0 4 OCIE1A R/W 0 3 TOIE1 R/W 0 2 OCIE0B R/W 0 1 OCIE0A R/W 0 0 TOIE0 R/W 0 TIMSK
* Bit 7 - ICIE1: Timer/Counter1, Input Capture Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter1 Input Capture interrupt is enabled. The corresponding Interrupt Vector (See "Interrupts" on page 40.) is executed when the ICF1 flag, located in TIFR, is set. * Bit 6 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 5 - OCIE1B: Timer/Counter1 Output Compare Match B Interrupt Enable When the OCIE1B bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter Compare Match B interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter occurs, i.e., when the OCF1B bit is set in the Timer/Counter Interrupt Flag Register - TIFR1. * Bit 4 - OCIE1A: Timer/Counter1 Output Compare Match A Interrupt Enable When the OCIE1A bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter1 Compare Match A interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter1 occurs, i.e., when the OCF1A bit is set in the Timer/Counter 1 Interrupt Flag Register - TIFR1. * Bit 3 - TOIE1: Timer/Counter1 Overflow Interrupt Enable When the TOIE1 bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter1 Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter1 occurs, i.e., when the TOV1 bit is set in the Timer/Counter 1 Interrupt Flag Register - TIFR1.
96
ATtiny40
8263A-AVR-08/10
ATtiny40
12.10.7 TIFR - Timer/Counter1 Interrupt Flag Register
Bit 0x25 Read/Write Initial Value 7 ICF1 R/W 0 6 - R 0 5 OCF1B R/W 0 4 OCF1A R/W 0 3 TOV1 R/W 0 2 OCF0B R/W 0 1 OCF0A R/W 0 0 TOV0 R/W 0 TIFR
* Bit 7 - ICF1: Timer/Counter1, Input Capture Flag This flag is set when a capture event occurs on the ICP1 pin. When the Input Capture Register (ICR1) is set to be used as the TOP value, the ICF1 flag is set when the counter reaches the TOP value. ICF1 is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICF1 can be cleared by writing a logic one to its bit location. * Bit 6 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 5 - OCF1B: Output Compare Flag 1 B The OCF1B bit is set when a Compare Match occurs between the Timer/Counter and the data in OCR1B - Output Compare Register1 B. OCF1B is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF1B is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE1B (Timer/Counter Compare B Match Interrupt Enable), and OCF1B are set, the Timer/Counter Compare Match Interrupt is executed. The OCF1B is not set in 16-bit Output Compare mode when the Output Compare Register OCR1B is used as the high byte of the 16-bit Output Compare Register or in 16-bit Input Capture mode when the Output Compare Register OCR1B is used as the high byte of the Input Capture Register. * Bit 4 - OCF1A: Output Compare Flag 1 A The OCF1A bit is set when a Compare Match occurs between the Timer/Counter1 and the data in OCR1A - Output Compare Register1. OCF1A is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCF1A is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIE1A (Timer/Counter1 Compare Match Interrupt Enable), and OCF1A are set, the Timer/Counter1 Compare Match Interrupt is executed. The OCF1A is also set in 16-bit mode when a Compare Match occurs between the Timer/Counter and 16-bit data in OCR1B/A. The OCF1A is not set in Input Capture mode when the Output Compare Register OCR1A is used as an Input Capture Register. * Bit 3 - TOV1: Timer/Counter1 Overflow Flag The bit TOV1 is set when an overflow occurs in Timer/Counter1. TOV1 is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOV1 is cleared by writing a logic one to the flag. When the SREG I-bit, TOIE1 (Timer/Counter1 Overflow Interrupt Enable), and TOV1 are set, the Timer/Counter1 Overflow interrupt is executed.
97
8263A-AVR-08/10
13. Timer/Counter Prescaler
Timer/Counter0 and Timer/Counter1 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counters. Tn is used as a general name, n = 0, 1. The Timer/Counter can be clocked directly by the system clock (by setting the CSn[2:0] = 1). This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system clock frequency (fCLK_I/O). Alternatively, one of four taps from the prescaler can be used as a clock source. The prescaled clock has a frequency of either f CLK_I/O /8, f CLK_I/O /64, fCLK_I/O/256, or fCLK_I/O/1024.
13.1
Prescaler Reset
The prescaler is free running, i.e., operates independently of the Clock Select logic of the Timer/CounterCounter, and it is shared by the Timer/Counter Tn. Since the prescaler is not affected by the Timer/Counter's clock select, the state of the prescaler will have implications for situations where a prescaled clock is used. One example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (CSn[2:0] = 2, 3, 4, or 5). The number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024). It is possible to use the Prescaler Reset for synchronizing the Timer/Counter to program execution.
13.2
External Clock Source
An external clock source applied to the Tn pin can be used as Timer/Counter clock (clkTn). The Tn pin is sampled once every system clock cycle by the pin synchronization logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 13-1 shows a functional equivalent block diagram of the Tn synchronization and edge detector logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch is transparent in the high period of the internal system clock. The edge detector generates one clk T0 pulse for each positive (CSn[2:0] = 7) or negative (CSn[2:0] = 6) edge it detects. Figure 13-1. T0 Pin Sampling
Tn
D LE
Q
D
Q
D
Q
Tn_sync (To Clock Select Logic)
clk I/O
Synchronization Edge Detector
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the Tn pin to the counter is updated.
98
ATtiny40
8263A-AVR-08/10
ATtiny40
Enabling and disabling of the clock input must be done when Tn has been stable for at least one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated. Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5. An external clock source can not be prescaled. Figure 13-2. Prescaler for Timer/Counter0
clk I/O
Clear
PSR
T0
Synchronization
clkT0
Note:
1. The synchronization logic on the input pins (T0) is shown in Figure 13-1 on page 98.
99
8263A-AVR-08/10
13.3
13.3.1
Register Description
TCCR0B - Timer/Counter Control Register B
Bit 0x18 Read/Write Initial Value 7 FOC0A W 0 6 FOC0B W 0 5 TSM R/W 0 4 PSR R/W 0 3 WGM02 R/W 0 2 CS02 R/W 0 1 CS01 R/W 0 0 CS00 R/W 0 TCCR0B
* Bit 5 - TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value that is written to the PSR bit is kept, hence keeping the Prescaler Reset signal asserted. This ensures that the Timer/Counter is halted and can be configured without the risk of advancing during configuration. When the TSM bit is written to zero, the PSR bit is cleared by hardware, and the Timer/Counter start counting. * Bit 4 - PSR: Prescaler Reset Timer/Counter When this bit is one, the Timer/Counter prescaler will be Reset. This bit is normally cleared immediately by hardware, except if the TSM bit is set.
100
ATtiny40
8263A-AVR-08/10
ATtiny40
14. Analog Comparator
The analog comparator compares the input values on the positive pin AIN0 and negative pin AIN1. When the voltage on the positive pin AIN0 is higher than the voltage on the negative pin AIN1, the Analog Comparator Output, ACO, is set. The comparator can trigger a separate interrupt, exclusive to the Analog Comparator. The user can select Interrupt triggering on comparator output rise, fall or toggle. A block diagram of the comparator and its surrounding logic is shown in Figure 14-1. Figure 14-1. Analog Comparator Block Diagram
BANDGAP REFERENCE ACBG ACD ACIE AIN0 + _ AIN1 ACIS1 ACIS0 ACIC HSEL HLEV ADC MULTIPLEXER OUTPUT (1) To T/C1 Capture Trigger MUX ACO INTERRUPT SELECT ANALOG COMPARATOR IRQ ACI VCC
ACME
Notes:
1. See Table 14-1 on page 102.
See Figure 1-1 on page 2 and Table 10-9 on page 58 for Analog Comparator pin placement. The ADC Power Reduction bit, PRADC, must be disabled in order to use the ADC input multiplexer. This is done by clearing the PRADC bit in the Power Reduction Register, PRR. See "PRR - Power Reduction Register" on page 31 for more details. When the supply voltage is below 2.7V, it is recommended to disable the ADC Power Reduction bit, PRADC, in order to use AIN0, AIN1, or a bandgap reference as an analog comparator input.
101
8263A-AVR-08/10
14.1
Analog Comparator Multiplexed Input
When the Analog to Digital Converter (ADC) is configurated as single ended input channel, it is possible to select any of the ADC[7:0] pins to replace the negative input to the Analog Comparator. The ADC multiplexer is used to select this input. If the Analog Comparator Multiplexer Enable bit (ACME in ADCSRB) is set, MUX bits in ADMUX select the input pin to replace the negative input to the analog comparator. Table 14-1.
ACME 0 1 1 1 1 1 1 1 1 1 1 1 1
Analog Comparator Multiplexed Input
MUX[3:0] XXXX 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 Analog Comparator Negative Input AIN1 ADC0 ADC1 ADC2 ADC3 ADC4 ADC5 ADC6 ADC7 ADC8 ADC9 ADC10 ADC11
14.2
14.2.1
Register Description
ACSRA - Analog Comparator Control and Status Register
Bit 0x14 Read/Write Initial Value 7 ACD R/W 0 6 ACBG R/W 0 5 ACO R N/A 4 ACI R/W 0 3 ACIE R/W 0 2 ACIC R/W 0 1 ACIS1 R/W 0 0 ACIS0 R/W 0 ACSRA
* Bit 7 - ACD: Analog Comparator Disable When this bit is written logic one, the power to the Analog Comparator is switched off. This bit can be set at any time to turn off the Analog Comparator. This will reduce power consumption in Active and Idle mode. When changing the ACD bit, the Analog Comparator Interrupt must be disabled by clearing the ACIE bit in ACSR. Otherwise an interrupt can occur when the bit is changed. * Bit 6 - ACBG: Analog Comparator Bandgap Select When this bit is set, a fixed, internal bandgap reference voltage replaces the positive input to the Analog Comparator. When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator.
102
ATtiny40
8263A-AVR-08/10
ATtiny40
* Bit 5 - ACO: Analog Comparator Output The output of the Analog Comparator is synchronized and then directly connected to ACO. The synchronization introduces a delay of 1 - 2 clock cycles. * Bit 4 - ACI: Analog Comparator Interrupt Flag This bit is set by hardware when a comparator output event triggers the interrupt mode defined by ACIS1 and ACIS0. The Analog Comparator interrupt routine is executed if the ACIE bit is set and the I-bit in SREG is set. ACI is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ACI is cleared by writing a logic one to the flag. * Bit 3 - ACIE: Analog Comparator Interrupt Enable When the ACIE bit is written logic one and the I-bit in the Status Register is set, the Analog Comparator interrupt is activated. When written logic zero, the interrupt is disabled. * Bit 2 - ACIC: Analog Comparator Input Capture Enable When written logic one, this bit enables the input capture function in Timer/Counter1 to be triggered by the Analog Comparator. The comparator output is then directly connected to the input capture front-end logic, making the comparator utilize the noise canceler and edge select features of the Timer/Counter1 Input Capture interrupt. When written logic zero, no connection between the Analog Comparator and the input capture function exists. To make the comparator trigger the Timer/Counter1 Input Capture inter-rupt, the ICIE1 bit in the Timer Interrupt Mask Register (TIMSK) must be set. * Bits 1:0 - ACIS[1:0]: Analog Comparator Interrupt Mode Select These bits determine which comparator events that trigger the Analog Comparator interrupt. The different settings are shown in Table 14-2. Table 14-2.
ACIS1 0 0 1 1
ACIS1/ACIS0 Settings
ACIS0 0 1 0 1 Interrupt Mode Comparator Interrupt on Output Toggle. Reserved Comparator Interrupt on Falling Output Edge. Comparator Interrupt on Rising Output Edge.
When changing the ACIS1/ACIS0 bits, the Analog Comparator Interrupt must be disabled by clearing its Interrupt Enable bit in the ACSR Register. Otherwise an interrupt can occur when the bits are changed. 14.2.2 ACSRB - Analog Comparator Control and Status Register B
Bit 0x13 Read/Write Initial Value 7 HSEL R/W 0 6 HLEV R/W 0 5 ACLP R/W 0 4 - R 0 3 ACCE R/W 0 2 ACME R/W 0 1 ACIRS1 R/W 0 0 ACIRS0 R/W 0 ACSRB
* Bit 7 - HSEL: Hysteresis Select When this bit is written logic one, the hysteresis of the analog comparator is enabled. The level of hysteresis is selected by the HLEV bit.
103
8263A-AVR-08/10
* Bit 6 - HLEV: Hysteresis Level When enabled via the HSEL bit, the level of hysteresis can be set using the HLEV bit, as shown in Table 14-3. Table 14-3.
HSEL 0 1
Selecting Level of Analog Comparator Hysteresis
HLEV X 0 1 Hysteresis of Analog Comparator Not enabled 20 mV 50 mV
* Bit 5 - ACLP This bit is reserved for QTouch, always write as zero. * Bit 4 - Reserved This bit is reserved and will always read as zero. * Bit 3 - ACCE This bit is reserved for QTouch, always write as zero. * Bit 2 - ACME: Analog Comparator Multiplexer Enable When this bit is written logic one and the ADC is switched off (ADEN in ADCSRA is zero), the ADC multiplexer selects the negative input to the Analog Comparator. When this bit is written logic zero, AIN1 is applied to the negative input of the Analog Comparator. For a detailed description of this bit, see "Analog Comparator Multiplexed Input" on page 102. * Bit 1 - ACIRS1 This bit is reserved for QTouch, always write as zero. * Bit 0 - ACIRS0 This bit is reserved for QTouch, always write as zero. 14.2.3 DIDR0 - Digital Input Disable Register 0
Bit 0x0D Read/Write Initial Value 7 ADC7D R/W 0 6 ADC6D R/W 0 5 ADC5D R/W 0 4 ADC4D R/W 0 3 ADC3D R/W 0 2 ADC2D R/W 0 1 ADC1D R/W 0 0 ADC0D R/W 0 DIDR0
* Bits 2:1 - ADC2D, ADC1D: ADC[2:1] Digital Input Buffer Disable When this bit is written logic one, the digital input buffer on the AIN[1:0] pin is disabled. The corresponding PIN Register bit will always read as zero when this bit is set. When used as an analog input but not required as a digital input the power consumption in the digital input buffer can be reduced by writing this bit to logic one.
104
ATtiny40
8263A-AVR-08/10
ATtiny40
15. Analog to Digital Converter
15.1 Features
* * * * * * * * * * * * * *
10-bit Resolution 1 LSB Integral Non-linearity 2 LSB Absolute Accuracy 13 s Conversion Time 15 kSPS at Maximum Resolution 12 Multiplexed Single Ended Input Channels Temperature Sensor Input Channel Optional Left Adjustment for ADC Result Readout 0 - VCC ADC Input Voltage Range 1.1V ADC Reference Voltage Free Running or Single Conversion Mode ADC Start Conversion by Auto Triggering on Interrupt Sources Interrupt on ADC Conversion Complete Sleep Mode Noise Canceler
15.2
Overview
ATtiny40 features a 10-bit, successive approximation Analog-to-Digital Converter (ADC). The ADC is wired to a 13-channel analog multiplexer, which allows the ADC to measure the voltage at 12 single-ended input pins, or from one internal, single-ended voltage channel coming from the internal temperature sensor. Voltage inputs are referred to 0V (GND). The ADC contains a Sample and Hold circuit which ensures that the input voltage to the ADC is held at a constant level during conversion. A block diagram of the ADC is shown in Figure 15-1 on page 106. Internal reference voltage of nominally 1.1V is provided on-chip. Alternatively, VCC can be used as reference voltage for single ended channels.
105
8263A-AVR-08/10
Figure 15-1. Analog to Digital Converter Block Schematic
8-BIT DATA BUS
ADMUX
MUX[3:0] REFS ADLAR
ADCSRB
ADTS[2:0]
INTERRUPT FLAGS
ADCSRA
ADPS2 ADPS1 ADPS0 ADSC ADATE ADEN ADIE
ADCH+ADCL
DECODER
CHANNEL
TRIGGER SELECT
START
ADC IRQ
PRESCALER
ADC[9:0] ADIF
CONVERSION LOGIC VCC
INTERNAL REFERENCE
10-BIT DAC
+
SAMPLE & HOLD COMPARATOR
TEMPERATURE SENSOR
ADC11 ADC10 ADC9 ADC8 ADC7 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 INPUT MUX
ADC MUX OUTPUT
AGND
15.3
Operation
In order to be able to use the ADC the Power Reduction bit, PRADC, in the Power Reduction Register must be disabled. This is done by clearing the PRADC bit. See "PRR - Power Reduction Register" on page 31 for more details. The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA. Voltage reference and input channel selections will not go into effect until ADEN is set. The ADC does not consume power when ADEN is cleared, so it is recommended to switch off the ADC before entering power saving sleep modes.
106
ATtiny40
8263A-AVR-08/10
ATtiny40
The ADC converts an analog input voltage to a 10-bit digital value using successive approximation. The minimum value represents GND and the maximum value represents the reference voltage. The ADC voltage reference is selected by writing the REFS bit in the ADMUX register. Alternatives are the VCC supply pin and the internal 1.1V voltage reference. The analog input channel is selected by writing to the MUX bits in ADMUX. Any of the ADC input pins can be selected as single ended inputs to the ADC. The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and ADCL. By default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the ADLAR bit in ADCSRB. If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH, only. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the data registers belongs to the same conversion. Once ADCL is read, ADC access to data registers is blocked. This means that if ADCL has been read, and a conversion completes before ADCH is read, neither register is updated and the result from the conversion is lost. When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled. The ADC has its own interrupt which can be triggered when a conversion completes. When ADC access to the data registers is prohibited between reading of ADCH and ADCL, the interrupt will trigger even if the result is lost.
15.4
Starting a Conversion
Make sure the ADC is powered by clearing the ADC Power Reduction bit, PRADC, in the Power Reduction Register, PRR (see "PRR - Power Reduction Register" on page 31). A single conversion is started by writing a logical one to the ADC Start Conversion bit, ADSC. This bit stays high as long as the conversion is in progress and will be cleared by hardware when the conversion is completed. If a different data channel is selected while a conversion is in progress, the ADC will finish the current conversion before performing the channel change. Alternatively, a conversion can be triggered automatically by various sources. Auto Triggering is enabled by setting the ADC Auto Trigger Enable bit, ADATE in ADCSRA. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB (see description of the ADTS bits for a list of the trigger sources). When a positive edge occurs on the selected trigger signal, the ADC prescaler is reset and a conversion is started. This provides a method of starting conversions at fixed intervals. If the trigger signal still is set when the conversion completes, a new conversion will not be started. If another positive edge occurs on the trigger signal during conversion, the edge will be ignored. Note that an Interrupt Flag will be set even if the specific interrupt is disabled or the Global Interrupt Enable bit in SREG is cleared. A conversion can thus be triggered without causing an interrupt. However, the Interrupt Flag must be cleared in order to trigger a new conversion at the next interrupt event.
107
8263A-AVR-08/10
Figure 15-2. ADC Auto Trigger Logic
ADTS[2:0] PRESCALER
START ADIF SOURCE 1 . . . . SOURCE n ADSC ADATE
CLKADC
CONVERSION LOGIC EDGE DETECTOR
Using the ADC Interrupt Flag as a trigger source makes the ADC start a new conversion as soon as the ongoing conversion has finished. The ADC then operates in Free Running mode, constantly sampling and updating the ADC Data Register. The first conversion must be started by writing a logical one to the ADSC bit in ADCSRA. In this mode the ADC will perform successive conversions independently of whether the ADC Interrupt Flag, ADIF is cleared or not. If Auto Triggering is enabled, single conversions can be started by writing ADSC in ADCSRA to one. ADSC can also be used to determine if a conversion is in progress. The ADSC bit will be read as one during a conversion, independently of how the conversion was started.
15.5
Prescaling and Conversion Timing
By default, the successive approximation circuitry requires an input clock frequency between 50 kHz and 200 kHz to get maximum resolution. If a lower resolution than 10 bits is needed, the input clock frequency to the ADC can be higher than 200 kHz to get a higher sample rate. It is not recommended to use a higher input clock frequency than 1 MHz. Figure 15-3. ADC Prescaler
ADEN START CK Reset 7-BIT ADC PRESCALER
ADPS0 ADPS1 ADPS2
ADC CLOCK SOURCE
The ADC module contains a prescaler, as illustrated in Figure 15-3 on page 108, which generates an acceptable ADC clock frequency from any CPU frequency above 100 kHz. The 108
ATtiny40
8263A-AVR-08/10
CK/128
CK/16
CK/32
CK/64
CK/2
CK/4
CK/8
ATtiny40
prescaling is set by the ADPS bits in ADCSRA. The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low. When initiating a single ended conversion by setting the ADSC bit in ADCSRA, the conversion starts at the following rising edge of the ADC clock cycle. A normal conversion takes 13 ADC clock cycles, as summarised in Table 15-1 on page 111. The first conversion after the ADC is switched on (ADEN in ADCSRA is set) takes 25 ADC clock cycles in order to initialize the analog circuitry, as shown in Figure 15-4 below. Figure 15-4. ADC Timing Diagram, First Conversion (Single Conversion Mode)
First Conversion Next Conversion
Cycle Number
1
2
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1
2
3
ADC Clock ADEN ADSC ADIF ADCH ADCL Sign and MSB of Result LSB of Result
MUX and REFS Update
Sample & Hold
Conversion Complete
MUX and REFS Update
The actual sample-and-hold takes place 1.5 ADC clock cycles after the start of a normal conversion and 13.5 ADC clock cycles after the start of a first conversion. See Figure 15-5. When a conversion is complete, the result is written to the ADC Data Registers, and ADIF is set. In Single Conversion mode, ADSC is cleared simultaneously. The software may then set ADSC again, and a new conversion will be initiated on the first rising ADC clock edge. Figure 15-5. ADC Timing Diagram, Single Conversion
One Conversion Next Conversion
Cycle Number ADC Clock ADSC ADIF ADCH ADCL
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
Sign and MSB of Result LSB of Result Sample & Hold MUX and REFS Update Conversion Complete
MUX and REFS Update
When Auto Triggering is used, the prescaler is reset when the trigger event occurs, as shown in Figure 15-6 below. This assures a fixed delay from the trigger event to the start of conversion. In
109
8263A-AVR-08/10
this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic. Figure 15-6. ADC Timing Diagram, Auto Triggered Conversion
One Conversion Next Conversion
Cycle Number ADC Clock Trigger Source ADATE ADIF ADCH ADCL
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
Sign and MSB of Result LSB of Result Sample & Hold MUX and REFS Update Conversion Complete Prescaler Reset
Prescaler Reset
In Free Running mode, a new conversion will be started immediately after the conversion completes, while ADSC remains high. See Figure 15-7. Figure 15-7. ADC Timing Diagram, Free Running Conversion
One Conversion 12 13 14 Next Conversion 1 2 3 4
Cycle Number ADC Clock ADSC ADIF ADCH ADCL
Sign and MSB of Result LSB of Result
Conversion Complete
Sample & Hold MUX and REFS Update
110
ATtiny40
8263A-AVR-08/10
ATtiny40
For a summary of conversion times, see Table 15-1. Table 15-1.
Condition First conversion Normal conversions Auto Triggered conversions Free Running conversion
ADC Conversion Time
Sample & Hold (Cycles from Start of Conversion) 13.5 1.5 2 2.5 Conversion Time (Cycles) 25 13 13.5 14
15.6
Changing Channel or Reference Selection
The MUX and REFS bits in the ADMUX Register are single buffered through a temporary register to which the CPU has random access. This ensures that the channels and reference selection only takes place at a safe point during the conversion. The channel and reference selection is continuously updated until a conversion is started. Once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the ADC. Continuous updating resumes in the last ADC clock cycle before the conversion completes (ADIF in ADCSRA is set). Note that the conversion starts on the following rising ADC clock edge after ADSC is written. The user is thus advised not to write new channel or reference selection values to ADMUX until one ADC clock cycle after ADSC is written. If Auto Triggering is used, the exact time of the triggering event can be indeterministic. Special care must be taken when updating the ADMUX Register, in order to control which conversion will be affected by the new settings. If both ADATE and ADEN is written to one, an interrupt event can occur at any time. If the ADMUX Register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. ADMUX can be safely updated in the following ways: * When ADATE or ADEN is cleared. * During conversion, minimum one ADC clock cycle after the trigger event. * After a conversion, before the Interrupt Flag used as trigger source is cleared. When updating ADMUX in one of these conditions, the new settings will affect the next ADC conversion.
15.6.1
ADC Input Channels When changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: * In Single Conversion mode, always select the channel before starting the conversion. The channel selection may be changed one ADC clock cycle after writing one to ADSC. However, the simplest method is to wait for the conversion to complete before changing the channel selection. * In Free Running mode, always select the channel before starting the first conversion. The channel selection may be changed one ADC clock cycle after writing one to ADSC. However, the simplest method is to wait for the first conversion to complete, and then change the 111
8263A-AVR-08/10
channel selection. Since the next conversion has already started automatically, the next result will reflect the previous channel selection. Subsequent conversions will reflect the new channel selection. 15.6.2 ADC Voltage Reference The ADC reference voltage (VREF) indicates the conversion range for the ADC. Single ended channels that exceed VREF will result in codes close to 0x3FF. VREF can be selected as either VCC, or internal 1.1V reference. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result.
15.7
ADC Noise Canceler
The ADC features a noise canceler that enables conversion during sleep mode. This reduces noise induced from the CPU core and other I/O peripherals. The noise canceler can be used with ADC Noise Reduction and Idle mode. To make use of this feature, the following procedure should be used: * Make sure that the ADC is enabled and is not busy converting. Single Conversion mode must be selected and the ADC conversion complete interrupt must be enabled. * Enter ADC Noise Reduction mode (or Idle mode). The ADC will start a conversion once the CPU has been halted. * If no other interrupts occur before the ADC conversion completes, the ADC interrupt will wake up the CPU and execute the ADC Conversion Complete interrupt routine. If another interrupt wakes up the CPU before the ADC conversion is complete, that interrupt will be executed, and an ADC Conversion Complete interrupt request will be generated when the ADC conversion completes. The CPU will remain in active mode until a new sleep command is executed. Note that the ADC will not automatically be turned off when entering other sleep modes than Idle mode and ADC Noise Reduction mode. The user is advised to write zero to ADEN before entering such sleep modes to avoid excessive power consumption.
15.8
Analog Input Circuitry
The analog input circuitry for single ended channels is illustrated in Figure 15-8. An analog source applied to ADCn is subjected to the pin capacitance and input leakage of that pin, regardless of whether that channel is selected as input for the ADC. When the channel is selected, the source must drive the S/H capacitor through the series resistance (combined resistance in the input path). The ADC is optimized for analog signals with an output impedance of approximately 10 k or less. If such a source is used, the sampling time will be negligible. If a source with higher impedance is used, the sampling time will depend on how long time the source needs to charge the S/H capacitor, which can vary widely. With slowly varying signals the user is recommended to use sources with low impedance, only, since this minimizes the required charge transfer to the S/H capacitor.
112
ATtiny40
8263A-AVR-08/10
ATtiny40
In order to avoid distortion from unpredictable signal convolution, signal components higher than the Nyquist frequency (fADC/2) should not be present. The user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the ADC. Figure 15-8. Analog Input Circuitry
IIH ADCn 1..100 kohm CS/H= 14 pF IIL VCC/2
Note: The capacitor in the figure depicts the total capacitance, including the sample/hold capacitor and any stray or parasitic capacitance inside the device. The value given is worst case.
15.9
Noise Canceling Techniques
Digital circuitry inside and outside the device generates EMI which might affect the accuracy of analog measurements. When conversion accuracy is critical, the noise level can be reduced by applying the following techniques: * Keep analog signal paths as short as possible. * Make sure analog tracks run over the analog ground plane. * Keep analog tracks well away from high-speed switching digital tracks. * If any port pin is used as a digital output, it mustn't switch while a conversion is in progress. * Place bypass capacitors as close to VCC and GND pins as possible. Where high ADC accuracy is required it is recommended to use ADC Noise Reduction Mode, as described in Section 15.7 on page 112. This is especially the case when system clock frequency is above 1 MHz, or when the ADC is used for reading the internal temperature sensor, as described in Section 15.12 on page 116. A good system design with properly placed, external bypass capacitors does reduce the need for using ADC Noise Reduction Mode
15.10 ADC Accuracy Definitions
An n-bit single-ended ADC converts a voltage linearly between GND and V REF in 2 n steps (LSBs). The lowest code is read as 0, and the highest code is read as 2n-1. Several parameters describe the deviation from the ideal behavior, as follows:
113
8263A-AVR-08/10
* Offset: The deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 LSB). Ideal value: 0 LSB. Figure 15-9. Offset Error
Output Code
Ideal ADC Actual ADC
Offset Error
VREF Input Voltage
* Gain Error: After adjusting for offset, the Gain Error is found as the deviation of the last transition (0x3FE to 0x3FF) compared to the ideal transition (at 1.5 LSB below maximum). Ideal value: 0 LSB Figure 15-10. Gain Error
Output Code
Gain Error
Ideal ADC Actual ADC
VREF Input Voltage
114
ATtiny40
8263A-AVR-08/10
ATtiny40
* Integral Non-linearity (INL): After adjusting for offset and gain error, the INL is the maximum deviation of an actual transition compared to an ideal transition for any code. Ideal value: 0 LSB. Figure 15-11. Integral Non-linearity (INL)
Output Code
* Differential Non-linearity (DNL): The maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 LSB). Ideal value: 0 LSB. Figure 15-12. Differential Non-linearity (DNL)
INL
Ideal ADC Actual ADC VREF Input Voltage
Output Code 0xFF
1 LSB
DNL
0x00 0 VREF Input Voltage
115
8263A-AVR-08/10
* Quantization Error: Due to the quantization of the input voltage into a finite number of codes, a range of input voltages (1 LSB wide) will code to the same value. Always 0.5 LSB. * Absolute Accuracy: The maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. This is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. Ideal value: 0.5 LSB.
15.11 ADC Conversion Result
After the conversion is complete (ADIF is high), the conversion result can be found in the ADC Data Registers (ADCL, ADCH). The result is, as follows: V IN 1024 ADC = -------------------------V REF where VIN is the voltage on the selected input pin and VREF the selected voltage reference (see Table 15-3 on page 117 and Table 15-4 on page 117). 0x000 represents analog ground, and 0x3FF represents the selected reference voltage minus one LSB. The result is presented in onesided form, from 0x3FF to 0x000.
15.12 Temperature Measurement
The temperature measurement is based on an on-chip temperature sensor that is coupled to a single ended ADC channel. The temperature sensor is measured via channel ADC12 and is enabled by writing MUX bits in ADMUX register to "1110". The internal 1.1V reference must also be selected for the ADC reference source in the temperature sensor measurement. When the temperature sensor is enabled, the ADC converter can be used in single conversion mode to measure the voltage over the temperature sensor. The measured voltage has a linear relationship to the temperature as described in Table 15-2 The sensitivity is approximately 1 LSB / C and the accuracy depends on the method of user calibration. Typically, the measurement accuracy after a single temperature calibration is 10C, assuming calibration at room temperature. Better accuracies are achieved by using two temperature points for calibration. Table 15-2.
Temperature ADC
Temperature vs. Sensor Output Voltage (Typical Case)
-40C 230 LSB +25C 300 LSB +85C 370 LSB
The values described in Table 15-2 are typical values. However, due to process variation the temperature sensor output voltage varies from one chip to another. To be capable of achieving more accurate results the temperature measurement can be calibrated in the application software. The sofware calibration can be done using the formula:
T = k * [(ADCH << 8) | ADCL] + TOS
where ADCH and ADCL are the ADC data registers, k is the fixed slope coefficient and TOS is the temperature sensor offset. Typically, k is very close to 1.0 and in single-point calibration the coefficient may be omitted. Where higher accuracy is required the slope coefficient should be evaluated based on measurements at two temperatures.
116
ATtiny40
8263A-AVR-08/10
ATtiny40
15.13 Register Description
15.13.1 ADMUX - ADC Multiplexer Selection Register
Bit 0x10 Read/Write Initial Value 7 - R 0 6 REFS R/W 0 5 REFEN R/W 0 4 ADC0EN R/W 0 3 MUX3 R/W 0 2 MUX2 R/W 0 1 MUX1 R/W 0 0 MUX0 R/W 0 ADMUX
* Bit 7 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 6 - REFS: Reference Selection Bit This bit selects the voltage reference for the ADC, as shown in Table 15-3. Table 15-3.
REFS 0 1
Voltage Reference Selections for ADC
Voltage Reference Selection VCC used as analog reference Internal 1.1V voltage reference
If this bit is changed during a conversion, the change will not go in effect until this conversion is complete (ADIF in ADCSR is set). Also note, that when these bits are changed, the next conversion will take 25 ADC clock cycles. * Bit 5 - REFEN This bit is reserved for QTouch, always write as zero. * Bit 4 - ADC0EN This bit is reserved for QTouch, always write as zero. * Bits 3:0 - MUX[3:0]: Analog Channel and Gain Selection Bits The value of these bits selects which analog input is connected to the ADC, as shown in Table 15-4. Selecting channel ADC12 enables temperature measurement. Table 15-4.
ADC0 (PA0) ADC1 (PA1) ADC2 (PA2) ADC3 (PA3) ADC4 (PA4) ADC5 (PA5) ADC6 (PA6) ADC7 (PA7) ADC8 (PB0) ADC9 (PB1)
Single-Ended Input channel Selections
MUX[3:0] 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001
Single Ended Input
117
8263A-AVR-08/10
Table 15-4.
ADC10 (PB2) ADC11 (PB3) 0V (AGND) 1.1V (I Ref)
Single-Ended Input channel Selections (Continued)
MUX[3:0] 1010 1011 1100 1101 1110 1111
Single Ended Input
ADC12 (Temperature Sensor)(1) Reserved Notes: 1. See "Temperature Measurement" on page 116.
If these bits are changed during a conversion, the change will not go into effect until this conversion is complete (ADIF in ADCSRA is set). 15.13.2 15.13.2.1 ADCL and ADCH - ADC Data Register ADLAR = 0
Bit 0x0F 0x0E Read/Write Initial Value 15 - ADC7 7 R R 0 0 14 - ADC6 6 R R 0 0 13 - ADC5 5 R R 0 0 12 - ADC4 4 R R 0 0 11 - ADC3 3 R R 0 0 10 - ADC2 2 R R 0 0 9 ADC9 ADC1 1 R R 0 0 8 ADC8 ADC0 0 R R 0 0 ADCH ADCL
15.13.2.2
ADLAR = 1
Bit 0x0F 0x0E Read/Write Initial Value 15 ADC9 ADC1 7 R R 0 0 14 ADC8 ADC0 6 R R 0 0 13 ADC7 - 5 R R 0 0 12 ADC6 - 4 R R 0 0 11 ADC5 - 3 R R 0 0 10 ADC4 - 2 R R 0 0 9 ADC3 - 1 R R 0 0 8 ADC2 - 0 R R 0 0 ADCH ADCL
When an ADC conversion is complete, the result is found in these two registers. When ADCL is read, the ADC Data Register is not updated until ADCH is read. Consequently, if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read ADCH. Otherwise, ADCL must be read first, then ADCH. The ADLAR bit in ADCSRB, and the MUX bits in ADMUX affect the way the result is read from the registers. If ADLAR is set, the result is left adjusted. If ADLAR is cleared (default), the result is right adjusted. * ADC[9:0]: ADC Conversion Result These bits represent the result from the conversion, as detailed in "ADC Conversion Result" on page 116.
118
ATtiny40
8263A-AVR-08/10
ATtiny40
15.13.3 ADCSRA - ADC Control and Status Register A
Bit 0x12 Read/Write Initial Value 7 ADEN R/W 0 6 ADSC R/W 0 5 ADATE R/W 0 4 ADIF R/W 0 3 ADIE R/W 0 2 ADPS2 R/W 0 1 ADPS1 R/W 0 0 ADPS0 R/W 0 ADCSRA
* Bit 7 - ADEN: ADC Enable Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the ADC off while a conversion is in progress, will terminate this conversion. * Bit 6 - ADSC: ADC Start Conversion In Single Conversion mode, write this bit to one to start each conversion. In Free Running mode, write this bit to one to start the first conversion. The first conversion after ADSC has been written after the ADC has been enabled, or if ADSC is written at the same time as the ADC is enabled, will take 25 ADC clock cycles instead of the normal 13. This first conversion performs initialization of the ADC. ADSC will read as one as long as a conversion is in progress. When the conversion is complete, it returns to zero. Writing zero to this bit has no effect. * Bit 5 - ADATE: ADC Auto Trigger Enable When this bit is written to one, Auto Triggering of the ADC is enabled. The ADC will start a conversion on a positive edge of the selected trigger signal. The trigger source is selected by setting the ADC Trigger Select bits, ADTS in ADCSRB. * Bit 4 - ADIF: ADC Interrupt Flag This bit is set when an ADC conversion completes and the data registers are updated. The ADC Conversion Complete Interrupt is executed if the ADIE bit and the I-bit in SREG are set. ADIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, ADIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write on ADCSRA, a pending interrupt can be disabled. * Bit 3 - ADIE: ADC Interrupt Enable When this bit is written to one and the I-bit in SREG is set, the ADC Conversion Complete Interrupt is activated. * Bits 2:0 - ADPS[2:0]: ADC Prescaler Select Bits These bits determine the division factor between the system clock frequency and the input clock to the ADC. Table 15-5.
ADPS2 0 0 0 0 1
ADC Prescaler Selections
ADPS1 0 0 1 1 0 ADPS0 0 1 0 1 0 Division Factor 2 2 4 8 16
119
8263A-AVR-08/10
Table 15-5.
ADPS2 1 1 1
ADC Prescaler Selections (Continued)
ADPS1 0 1 1 ADPS0 1 0 1 Division Factor 32 64 128
15.13.4
ADCSRB - ADC Control and Status Register B
Bit 0x11 Read/Write Initial Value 7 VDEN R/W 0 6 VDPD R/W 0 5 - R 0 4 - R 0 3 ADLAR R/W 0 2 ADTS2 R/W 0 1 ADTS1 R/W 0 0 ADTS0 R/W 0 ADCSRB
* Bit 7 - VDEN This bit is reserved for QTouch, always write as zero. * Bit 6 - VDPD This bit is reserved for QTouch, always write as zero. * Bits 5:4 - Res: Reserved Bits These are reserved bits. For compatibility with future devices always write these bits to zero. * Bit 3 - ADLAR: ADC Left Adjust Result The ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register. Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted. Changing the ADLAR bit will affect the ADC Data Register immediately, regardless of any ongoing conversions. For a comple the description of this bit, see "ADCL and ADCH - ADC Data Register" on page 118. * Bits 2:0 - ADTS[2:0]: ADC Auto Trigger Source If ADATE in ADCSRA is written to one, the value of these bits selects which source will trigger an ADC conversion. If ADATE is cleared, the ADTS[2:0] settings will have no effect. A conversion will be triggered by the rising edge of the selected Interrupt Flag. Note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. If ADEN in ADCSRA is set, this will start a conversion. Switching to Free Running mode (ADTS[2:0]=0) will not cause a trigger event, even if the ADC Interrupt Flag is set. Table 15-6.
ADTS2 0 0 0 0 1
ADC Auto Trigger Source Selections
ADTS1 0 0 1 1 0 ADTS0 0 1 0 1 0 Trigger Source Free Running mode Analog Comparator External Interrupt Request 0 Timer/Counter0 Compare Match A Timer/Counter0 Overflow
120
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 15-6.
ADTS2 1 1 1
ADC Auto Trigger Source Selections (Continued)
ADTS1 0 1 1 ADTS0 1 0 1 Trigger Source Timer/Counter1 Compare Match B Timer/Counter1 Overflow Timer/Counter1 Capture Event
15.13.5
DIDR0 - Digital Input Disable Register 0
Bit 0x0D Read/Write Initial Value 7 ADC7D R/W 0 6 ADC6D R/W 0 5 ADC5D R/W 0 4 ADC4D R/W 0 3 ADC3D R/W 0 2 ADC2D R/W 0 1 ADC1D R/W 0 0 ADC0D R/W 0 DIDR0
* Bits 7:0 - ADC7D:ADC0D: ADC[7:0] Digital Input Disable When a bit is written logic one, the digital input buffer on the corresponding ADC pin is disabled. The corresponding PIN register bit will always read as zero when this bit is set. When an analog signal is applied to the ADC[7:0] pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. 15.13.6 PORTCR - Port Control Register
Bit 0x08 Read/Write Initial Value 7 ADC11D R/W 0 6 ADC10D R/W 0 5 ADC9D R/W 0 4 ADC8D R/W 0 3 - R 0 2 BBMC R/W 0 1 BBMB R/W 0 0 BBMA R/W 0 PORTCR
* Bits 7:4 - ADC11D:ADC8D: ADC[11:8] Digital Input Disable When a bit is written logic one, the digital input buffer on the corresponding ADC pin is disabled. The corresponding PIN register bit will always read as zero when this bit is set. When an analog signal is applied to the ADC[11:8] pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer.
121
8263A-AVR-08/10
16. SPI - Serial Peripheral Interface
16.1 Features
* * * * * * * *
Full-duplex, Three-wire Synchronous Data Transfer Master or Slave Operation LSB First or MSB First Data Transfer Seven Programmable Bit Rates End of Transmission Interrupt Flag Write Collision Flag Protection Wake-up from Idle Mode Double Speed (CK/2) Master SPI Mode
16.2
Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATtiny40 and peripheral devices or between several AVR devices. The SPI module is illustrated in Figure 16-1. Figure 16-1. SPI Block Diagram
CLKIO
DIVIDER /2/4/8/16/32/64/128
SS SPI2X
Note:
Refer to Figure 1-1 on page 2, and Table 16-1 on page 124 for SPI pin placement.
122
ATtiny40
8263A-AVR-08/10
SPI2X
ATtiny40
To enable the SPI module, the PRSPI bit in the Power Reduction Register must be written to zero. See "PRR - Power Reduction Register" on page 31. The interconnection between Master and Slave CPUs with SPI is shown in Figure 16-2 on page 123. The system consists of two shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always shifted from Master to Slave on the Master Out - Slave In, MOSI, line, and from Slave to Master on the Master In - Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling high the Slave Select, SS, line. When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register for later use. When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use. Figure 16-2. SPI Master-Slave Interconnection
SHIFT ENABLE
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost. In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock signal, the minimum low and high periods should be: 123
8263A-AVR-08/10
Low periods: Longer than 2 CPU clock cycles. High periods: Longer than 2 CPU clock cycles. When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 16-1 on page 124. For more details on automatic port overrides, refer to "Alternate Port Functions" on page 52. Table 16-1.
Pin MOSI MISO SCK SS Note:
SPI Pin Overrides
Direction, Master SPI User Defined Input User Defined User Defined Direction, Slave SPI Input User Defined Input Input
See "Alternate Functions of Port B" on page 57 for a detailed description of how to define the direction of the user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB. Assembly Code Example(1)
SPI_MasterInit: ; Set MOSI and SCK output, all others input ldi out ldi out ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete in r16, SPSR sbrsr16, SPIF rjmp Wait_Transmit ret r17,(1<; Enable SPI, Master, set clock rate fck/16
124
ATtiny40
8263A-AVR-08/10
ATtiny40
C Code Example(1)
void SPI_MasterInit(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI = (1<The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example(1)
SPI_SlaveInit: ; Set MISO output, all others input ldi out ldi out ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in ret r16,SPDR r17,(1<; Enable SPI
125
8263A-AVR-08/10
C Code Example(1)
void SPI_SlaveInit(void) { /* Set MISO output, all others input */ DDR_SPI = (1<16.3
16.3.1
SS Pin Functionality
Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high. The SS pin is useful for packet/byte synchronization to keep the slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI slave will immediately reset the send and receive logic, and drop any partially received data in the Shift Register.
16.3.2
Master Mode When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI system interprets this as another master selecting the SPI as a slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions:
126
ATtiny40
8263A-AVR-08/10
ATtiny40
1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs. 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed. Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a slave select, it must be set by the user to re-enable SPI Master mode.
16.4
Data Modes
There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 16-3 on page 127 and Figure 16-4 on page 128. Figure 16-3. SPI Transfer Format with CPHA = 0
SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS
MSB first (DORD = 0) MSB LSB first (DORD = 1) LSB
Bit 6 Bit 1
Bit 5 Bit 2
Bit 4 Bit 3
Bit 3 Bit 4
Bit 2 Bit 5
Bit 1 Bit 6
LSB MSB
127
8263A-AVR-08/10
Figure 16-4. SPI Transfer Format with CPHA = 1
SCK (CPOL = 0) mode 1 SCK (CPOL = 1) mode 3 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS
MSB first (DORD = 0) LSB first (DORD = 1)
MSB LSB
Bit 6 Bit 1
Bit 5 Bit 2
Bit 4 Bit 3
Bit 3 Bit 4
Bit 2 Bit 5
Bit 1 Bit 6
LSB MSB
Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. This is shown in Table 16-2, which is a summary of Table 16-3 on page 129 and Table 16-4 on page 129. Table 16-2.
SPI Mode 0 1 2 3
SPI Modes
Conditions CPOL=0, CPHA=0 CPOL=0, CPHA=1 CPOL=1, CPHA=0 CPOL=1, CPHA=1 Leading Edge Sample (Rising) Setup (Rising) Sample (Falling) Setup (Falling) Trailing eDge Setup (Falling) Sample (Falling) Setup (Rising) Sample (Rising)
16.5
16.5.1
Register Description
SPCR - SPI Control Register
Bit 0x30 Read/Write Initial Value 7 SPIE R/W 0 6 SPE R/W 0 5 DORD R/W 0 4 MSTR R/W 0 3 CPOL R/W 0 2 CPHA R/W 0 1 SPR1 R/W 0 0 SPR0 R/W 0 SPCR
* Bit 7 - SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if the Global Interrupt Enable bit in SREG is set. * Bit 6 - SPE: SPI Enable When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. * Bit 5 - DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first.
128
ATtiny40
8263A-AVR-08/10
ATtiny40
When the DORD bit is written to zero, the MSB of the data word is transmitted first. * Bit 4 - MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode. * Bit 3 - CPOL: Clock Polarity When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 16-3 and Figure 16-4 for an example. The CPOL functionality is summarized below: Table 16-3. CPOL Functionality
CPOL 0 1 Leading Edge Rising Falling Trailing Edge Falling Rising
* Bit 2 - CPHA: Clock Phase The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. Refer to Figure 16-3 and Figure 16-4 for an example. The CPOL functionality is summarized below: Table 16-4. CPHA Functionality
CPHA 0 1 Leading Edge Sample Setup Trailing Edge Setup Sample
* Bits 1:0 - SPR[1:0]: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between SCK and the I/O Clock frequency fclk_I/O is shown in the following table: Table 16-5.
SPI2X 0 0 0 0 1 1 1 1
Relationship Between SCK and the I/O Clock Frequency
SPR1 0 0 1 1 0 0 1 1 SPR0 0 1 0 1 0 1 0 1 SCK Frequency
fclk_I/O/4 fclk_I/O/16 fclk_I/O/64 fclk_I/O/128 fclk_I/O/2 fclk_I/O/8 fclk_I/O/32 fclk_I/O/64
129
8263A-AVR-08/10
16.5.2
SPSR - SPI Status Register
Bit 0x2F Read/Write Initial Value 7 SPIF R/W 0 6 WCOL R/W 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 - R 0 0 SPI2X R/W 0 SPSR
* Bit 7 - SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). * Bit 6 - WCOL: Write COLlision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. * Bits 5:1 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 0 - SPI2X: Double SPI Speed Bit When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode (see Table 16-5). This means that the minimum SCK period will be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fclk_I/O/4 or lower. 16.5.3 SPDR - SPI Data Register
Bit 0x2E Read/Write Initial Value 7 MSB R/W X R/W X R/W X R/W X R/W X R/W X R/W X 6 5 4 3 2 1 0 LSB R/W X Undefined SPDR
The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read.
130
ATtiny40
8263A-AVR-08/10
ATtiny40
17. TWI - Two Wire Slave Interface
17.1 Features
* * * * * * * * * * *
Phillips I2C compatible SMBus compatible 100 kHz and 400 kHz support at low system clock frequencies Slew-Rate Limited Output Drivers Input Filter provides noise suppression 7-bit, and General Call Address Recognition in Hardware Address mask register for address masking or dual address match 10-bit addressing supported Optional Software Address Recognition Provides Unlimited Number of Slave Addresses Slave can operate in all sleep modes, including Power Down Slave Arbitration allows support for Address Resolve Protocol (ARP) (SMBus)
17.2
Overview
The Two Wire Interface (TWI) is a bi-directional, bus communication interface, which uses only two wires. TWI is I2C and SMBus compatible. A device connected to the bus must act as a master or slave.The master initiates a data transaction by addressing a slave on the bus, and telling whether it wants to transmit or receive data. One bus can have several masters, and an arbitration process handles priority if two or more masters try to transmit at the same time. The TWI module in ATtiny40 implements slave functionality, only. Lost arbitration, errors, collisions and clock holds on the bus are detected in hardware and indicated in separate status flags. Both 7-bit and general address call recognition is implemented in hardware. 10-bit addressing is also supported. A dedicated address mask register can act as a second address match register or as a mask register for the slave address to match on a range of addresses. The slave logic continues to operate in all sleep modes, including Power down. This enables the slave to wake up from sleep on TWI address match. It is possible to disable the address matching and let this be handled in software instead. This allows the slave to detect and respond to several addresses. Smart Mode can be enabled to auto trigger operations and reduce software complexity. The TWI module includes bus state logic that collects information to detect START and STOP conditions, bus collision and bus errors. The bus state logic continues to operate in all sleep modes including Power down.
17.3
General TWI Bus Concepts
The Two-Wire Interface (TWI) provides a simple two-wire bi-directional bus consisting of a serial clock line (SCL) and a serial data line (SDA). The two lines are open collector lines (wired-AND), and pull-up resistors (Rp) are the only external components needed to drive the bus. The pull-up resistors will provide a high level on the lines when none of the connected devices are driving the bus. A constant current source can be used as an alternative to the pull-up resistors. The TWI bus is a simple and efficient method of interconnecting multiple devices on a serial bus. A device connected to the bus can be a master or slave, where the master controls the bus and all communication.
131
8263A-AVR-08/10
Figure 17-1 illustrates the TWI bus topology. Figure 17-1. TWI Bus Topology
VCC
RP RP
TWI DEVICE #1
TWI DEVICE #2
TWI DEVICE #N
RS
RS
RS
RS
RS
RS
SDA SCL
Note: RS is optional
A unique address is assigned to all slave devices connected to the bus, and the master will use this to address a slave and initiate a data transaction. 7-bit or 10-bit addressing can be used. Several masters can be connected to the same bus, and this is called a multi-master environment. An arbitration mechanism is provided for resolving bus ownership between masters since only one master device may own the bus at any given time. A device can contain both master and slave logic, and can emulate multiple slave devices by responding to more than one address. A master indicates the start of transaction by issuing a START condition (S) on the bus. An address packet with a slave address (ADDRESS) and an indication whether the master wishes to read or write data (R/W), is then sent. After all data packets (DATA) are transferred, the master issues a STOP condition (P) on the bus to end the transaction. The receiver must acknowledge (A) or not-acknowledge (A) each byte received. Figure 17-2 shows a TWI transaction. Figure 17-2. Basic TWI Transaction Diagram Topology
SDA SCL
S 6 ... 0 ADDRESS R/W ACK 7 ... 0 DATA ACK 7 ... 0 DATA ACK/NACK P
S
ADDRESS
R/W
A
Direction
DATA
A
DATA
A/A
P
Address Packet
Data Packet #0 Transaction
Data Packet #1
The master provides data on the bus The master or slave can provide data on the bus The slave provides data on the bus
132
ATtiny40
8263A-AVR-08/10
ATtiny40
The master provides the clock signal for the transaction, but a device connected to the bus is allowed to stretch the low level period of the clock to decrease the clock speed. 17.3.1 Electrical Characteristics The TWI follows the electrical specifications and timing of I2C and SMBus. START and STOP Conditions Two unique bus conditions are used for marking the beginning (START) and end (STOP) of a transaction. The master issues a START condition(S) by indicating a high to low transition on the SDA line while the SCL line is kept high. The master completes the transaction by issuing a STOP condition (P), indicated by a low to high transition on the SDA line while SCL line is kept high. Figure 17-3. START and STOP Conditions
SDA SCL
S START Condition P STOP Condition
17.3.2
Multiple START conditions can be issued during a single transaction. A START condition not directly following a STOP condition, are named a Repeated START condition (Sr). 17.3.3 Bit Transfer As illustrated by Figure 17-4 a bit transferred on the SDA line must be stable for the entire high period of the SCL line. Consequently the SDA value can only be changed during the low period of the clock. This is ensured in hardware by the TWI module. Figure 17-4. Data Validity
SDA SCL
DATA Valid Change Allowed
Combining bit transfers results in the formation of address and data packets. These packets consist of 8 data bits (one byte) with the most significant bit transferred first, plus a single bit notacknowledge (NACK) or acknowledge (ACK) response. The addressed device signals ACK by pulling the SCL line low, and NACK by leaving the line SCL high during the ninth clock cycle.
133
8263A-AVR-08/10
17.3.4
Address Packet After the START condition, a 7-bit address followed by a read/write (R/W) bit is sent. This is always transmitted by the Master. A slave recognizing its address will ACK the address by pulling the data line low the next SCL cycle, while all other slaves should keep the TWI lines released, and wait for the next START and address. The 7-bit address, the R/W bit and the acknowledge bit combined is the address packet. Only one address packet for each START condition is given, also when 10-bit addressing is used. The R/W specifies the direction of the transaction. If the R/W bit is low, it indicates a Master Write transaction, and the master will transmit its data after the slave has acknowledged its address. Opposite, for a Master Read operation the slave will start to transmit data after acknowledging its address.
17.3.5
Data Packet Data packets succeed an address packet or another data packet. All data packets are nine bits long, consisting of one data byte and an acknowledge bit. The direction bit in the previous address packet determines the direction in which the data is transferred.
17.3.6
Transaction A transaction is the complete transfer from a START to a STOP condition, including any Repeated START conditions in between. The TWI standard defines three fundamental transaction modes: Master Write, Master Read, and combined transaction. Figure 17-5 illustrates the Master Write transaction. The master initiates the transaction by issuing a START condition (S) followed by an address packet with direction bit set to zero (ADDRESS+W). Figure 17-5. Master Write Transaction
Address Packet Transaction Data Packet
S
ADDRESS
W
A
DATA
A
N data packets
DATA
A/A
P
Given that the slave acknowledges the address, the master can start transmitting data (DATA) and the slave will ACK or NACK (A/A) each byte. If no data packets are to be transmitted, the master terminates the transaction by issuing a STOP condition (P) directly after the address packet. There are no limitations to the number of data packets that can be transferred. If the slave signal a NACK to the data, the master must assume that the slave cannot receive any more data and terminate the transaction. Figure 17-6 illustrates the Master Read transaction. The master initiates the transaction by issuing a START condition followed by an address packet with direction bit set to one (ADRESS+R). The addressed slave must acknowledge the address for the master to be allowed to continue the transaction.
134
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 17-6. Master Read Transaction
Address Packet Transaction Data Packet
S
ADDRESS
R
A
DATA
A
N data packets
DATA
A
P
Given that the slave acknowledges the address, the master can start receiving data from the slave. There are no limitations to the number of data packets that can be transferred. The slave transmits the data while the master signals ACK or NACK after each data byte. The master terminates the transfer with a NACK before issuing a STOP condition. Figure 17-7 illustrates a combined transaction. A combined transaction consists of several read and write transactions separated by a Repeated START conditions (Sr). Figure 17-7. Combined Transaction
Transaction Address Packet #1 N Data Packets Address Packet #2 M Data Packets
S
ADDRESS
R/W A
Direction
DATA
A/A Sr
ADDRESS
R/W A
Direction
DATA
A/A
P
17.3.7
Clock and Clock Stretching All devices connected to the bus are allowed to stretch the low period of the clock to slow down the overall clock frequency or to insert wait states while processing data. A device that needs to stretch the clock can do this by holding/forcing the SCL line low after it detects a low level on the line. Three types of clock stretching can be defined as shown in Figure 17-8. Figure 17-8. Clock Stretching
SDA SCL
S Wakeup clock stretching Periodic clock stretching Random clock stretching
bit 7
bit 6
bit 0
ACK/NACK
If the device is in a sleep mode and a START condition is detected the clock is stretched during the wake-up period for the device. A slave device can slow down the bus frequency by stretching the clock periodically on a bit level. This allows the slave to run at a lower system clock frequency. However, the overall performance of the bus will be reduced accordingly. Both the master and slave device can randomly stretch the clock on a byte level basis before and after the ACK/NACK bit. This provides time to process incoming or prepare outgoing data, or performing other time critical tasks.
135
8263A-AVR-08/10
In the case where the slave is stretching the clock the master will be forced into a wait-state until the slave is ready and vice versa. 17.3.8 Arbitration A master can only start a bus transaction if it has detected that the bus is idle. As the TWI bus is a multi master bus, it is possible that two devices initiate a transaction at the same time. This results in multiple masters owning the bus simultaneously. This is solved using an arbitration scheme where the master loses control of the bus if it is not able to transmit a high level on the SDA line. The masters who lose arbitration must then wait until the bus becomes idle (i.e. wait for a STOP condition) before attempting to reacquire bus ownership. Slave devices are not involved in the arbitration procedure. Figure 17-9. TWI Arbitration
DEVICE1 Loses arbitration
DEVICE1_SDA DEVICE2_SDA
SDA (wired-AND) SCL
S
bit 7
bit 6
bit 5
bit 4
Figure 17-9 shows an example where two TWI masters are contending for bus ownership. Both devices are able to issue a START condition, but DEVICE1 loses arbitration when attempting to transmit a high level (bit 5) while DEVICE2 is transmitting a low level. Arbitration between a repeated START condition and a data bit, a STOP condition and a data bit, or a repeated START condition and STOP condition are not allowed and will require special handling by software. 17.3.9 Synchronization A clock synchronization algorithm is necessary for solving situations where more than one master is trying to control the SCL line at the same time. The algorithm is based on the same principles used for clock stretching previously described. Figure 17-10 shows an example where two masters are competing for the control over the bus clock. The SCL line is the wired-AND result of the two masters clock outputs.
136
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 17-10. Clock Synchronization
Low Period Count Wait State High Period Count
DEVICE1_SCL
DEVICE2_SCL
SCL (wired-AND)
A high to low transition on the SCL line will force the line low for all masters on the bus and they start timing their low clock period. The timing length of the low clock period can vary between the masters. When a master (DEVICE1 in this case) has completed its low period it releases the SCL line. However, the SCL line will not go high before all masters have released it. Consequently the SCL line will be held low by the device with the longest low period (DEVICE2). Devices with shorter low periods must insert a wait-state until the clock is released. All masters start their high period when the SCL line is released by all devices and has become high. The device which first completes its high period (DEVICE1) forces the clock line low and the procedure are then repeated. The result of this is that the device with the shortest clock period determines the high period while the low period of the clock is determined by the longest clock period.
17.4
TWI Slave Operation
The TWI slave is byte-oriented with optional interrupts after each byte. There are separate interrupt flags for Data Interrupt and Address/Stop Interrupt. Interrupt flags can be set to trigger the TWI interrupt, or be used for polled operation. There are dedicated status flags for indicating ACK/NACK received, clock hold, collision, bus error and read/write direction. When an interrupt flag is set, the SCL line is forced low. This will give the slave time to respond or handle any data, and will in most cases require software interaction. Figure 17-11. shows the TWI slave operation. The diamond shapes symbols (SW) indicate where software interaction is required.
137
8263A-AVR-08/10
Figure 17-11. TWI Slave Operation
SLAVE ADDRESS INTERRUPT SLAVE DATA INTERRUPT P
S2 S3
DATA A A
S1 S2
S3
S ADDRESS R
SW
A A
S1
SW
Sr
S1
P A SW Driver software W The master provides data on the bus Slave provides data on the bus Interrupt on STOP Condition Enabled Collision (SMBus)
SW
S2 S3
DATA
SW
S1
Sr
A
A/A
SW
Release Hold
SW
S1
Sn
Diagram connections
The number of interrupts generated is kept at a minimum by automatic handling of most conditions. Quick Command can be enabled to auto trigger operations and reduce software complexity. Promiscuous Mode can be enabled to allow the slave to respond to all received addresses. 17.4.1 Receiving Address Packets When the TWI slave is properly configured, it will wait for a START condition to be detected. When this happens, the successive address byte will be received and checked by the address match logic, and the slave will ACK the correct address. If the received address is not a match, the slave will not acknowledge the address and wait for a new START condition. The slave Address/Stop Interrupt Flag is set when a START condition succeeded by a valid address packet is detected. A general call address will also set the interrupt flag. A START condition immediately followed by a STOP condition, is an illegal operation and the Bus Error flag is set. The R/W Direction flag reflects the direction bit received with the address. This can be read by software to determine the type of operation currently in progress. Depending on the R/W direction bit and bus condition one of four distinct cases (1 to 4) arises following the address packet. The different cases must be handled in software. 17.4.1.1 Case 1: Address packet accepted - Direction bit set If the R/W Direction flag is set, this indicates a master read operation. The SCL line is forced low, stretching the bus clock. If ACK is sent by the slave, the slave hardware will set the Data Interrupt Flag indicating data is needed for transmit. If NACK is sent by the slave, the slave will wait for a new START condition and address match. Case 2: Address packet accepted - Direction bit cleared If the R/W Direction flag is cleared this indicates a master write operation. The SCL line is forced low, stretching the bus clock. If ACK is sent by the slave, the slave will wait for data to be
17.4.1.2
138
ATtiny40
8263A-AVR-08/10
ATtiny40
received. Data, Repeated START or STOP can be received after this. If NACK is indicated the slave will wait for a new START condition and address match. 17.4.1.3 Case 3: Collision If the slave is not able to send a high level or NACK, the Collision flag is set and it will disable the data and acknowledge output from the slave logic. The clock hold is released. A START or repeated START condition will be accepted. Case 4: STOP condition received. Operation is the same as case 1 or 2 above with one exception. When the STOP condition is received, the Slave Address/Stop flag will be set indicating that a STOP condition and not an address match occurred. Receiving Data Packets The slave will know when an address packet with R/W direction bit cleared has been successfully received. After acknowledging this, the slave must be ready to receive data. When a data packet is received the Data Interrupt Flag is set, and the slave must indicate ACK or NACK. After indicating a NACK, the slave must expect a STOP or Repeated START condition. Transmitting Data Packets The slave will know when an address packet, with R/W direction bit set, has been successfully received. It can then start sending data by writing to the Slave Data register. When a data packet transmission is completed, the Data Interrupt Flag is set. If the master indicates NACK, the slave must stop transmitting data, and expect a STOP or Repeated START condition.
17.4.1.4
17.4.2
17.4.3
17.5
17.5.1
Register Description
TWSCRA - TWI Slave Control Register A
Bit 0x2D Read/Write Initial Value 7 6 5 4 3 2 1 0
TWSHE
R/W 0
-
R 0
TWDIE
R/W 0
TWASIE
R/W 0
TWEN
R/W 0
TWSIE
R/W 0
TWPME
R/W 0
TWSME
R/W 0
TWSCRA
* Bit 7 - TWSHE: TWI SDA Hold Time Enable When this bit is set the internal hold time on SDA with respect to the negative edge on SCL is enabled. * Bit 6 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bit 5 - TWDIE: TWI Data Interrupt Enable When this bit is set and interrupts are enabled, a TWI interrupt will be generated when the data interrupt flag (TWDIF) in TWSSRA is set. * Bit 4 - TWASIE: TWI Address/Stop Interrupt Enable When this bit is set and interrupts are enabled, a TWI interrupt will be generated when the address/stop interrupt flag (TWASIF) in TWSSRA is set. * Bit 3 - TWEN: Two-Wire Interface Enable When this bit is set the slave Two-Wire Interface is enabled. 139
8263A-AVR-08/10
* Bit 2 - TWSIE: TWI Stop Interrupt Enable Setting the Stop Interrupt Enable (TWSIE) bit will set the TWASIF in the TWSSRA register when a STOP condition is detected. * Bit 1 - TWPME: TWI Promiscuous Mode Enable When this bit is set the address match logic of the slave TWI responds to all received addresses. When this bit is cleared the address match logic uses the TWSA register to determine which address to recognize as its own. * Bit 0 - TWSME: TWI Smart Mode Enable When this bit is set the TWI slave enters Smart Mode, where the Acknowledge Action is sent immediately after the TWI data register (TWSD) has been read. Acknowledge Action is defined by the TWAA bit in TWSCRB. When this bit is cleared the Acknowledge Action is sent after TWCMDn bits in TWSCRB are written to 1X. 17.5.2 TWSCRB - TWI Slave Control Register B
Bit 0x2C Read/Write Initial Value 7 6 5 4 3 2 1 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
TWAA
R/W 0
TWCMD1
W 0
TWCMD0
W 0
TWSCRB
* Bits 7:3 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 2 - TWAA: TWI Acknowledge Action This bit defines the slave's acknowledge behavior after an address or data byte has been received from the master. Depending on the TWSME bit in TWSCRA the Acknowledge Action is executed either when a valid command has been written to TWCMDn bits, or when the data register has been read. Acknowledge action is also executed if clearing TWAIF flag after address match or TWDIF flag during master transmit. See Table 17-1 for details. Table 17-1.
TWAA 0
Acknowledge Action of TWI Slave
Action Send ACK TWSME 0 1 0 1 When When TWCMDn bits are written to 10 or 11 When TWSD is read When TWCMDn bits are written to 10 or 11 When TWSD is read
1
Send NACK
* Bits 1:0 - TWCMD[1:0]: TWI Command Writing these bits triggers the slave operation as defined by Table 17-2. The type of operation depends on the TWI slave interrupt flags, TWDIF and TWASIF. The Acknowledge Action is only executed when the slave receives data bytes or address byte from the master.
140
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 17-2.
TWCMD[1:0] 00 01
TWI Slave Command
TWDIR X X Operation No action Reserved
Used to complete transaction 10 0 1 Execute Acknowledge Action, then wait for any START (S/Sr) condition Wait for any START (S/Sr) condition
Used in response to an Address Byte (TWASIF is set) 0 11 1 Execute Acknowledge Action, then receive next byte Execute Acknowledge Action, then set TWDIF
Used in response to a Data Byte (TWDIF is set) 0 1 Execute Acknowledge Action, then wait for next byte No action
Writing the TWCMD bits will automatically release the SCL line and clear the TWCH and slave interrupt flags. TWAA and TWCMDn bits can be written at the same time. Acknowledge Action will then be executed before the command is triggered. The TWCMDn bits are strobed and always read zero. 17.5.3 TWSSRA - TWI Slave Status Register A
Bit 0x2B Read/Write Initial Value 7 6 5 4 3 2 1 0
TWDIF
R/W 0
TWASIF
R/W 0
TWCH
R 0
TWRA
R 0
TWC
R/W 0
TWBE
R/W 0
TWDIR
R/W 0
TWAS
R/W 0
TWSCRA
* Bit 7 - TWDIF: TWI Data Interrupt Flag This flag is set when a data byte has been successfully received, i.e. no bus errors or collisions have occurred during the operation. When this flag is set the slave forces the SCL line low, stretching the TWI clock period. The SCL line is released by clearing the interrupt flags. Writing a one to this bit will clear the flag. This flag is also automatically cleared when writing a valid command to the TWCMDn bits in TWSCRB. * Bit 6 - TWASIF: TWI Address/Stop Interrupt Flag This flag is set when the slave detects that a valid address has been received, or when a transmit collision has been detected. When this flag is set the slave forces the SCL line low, stretching the TWI clock period. The SCL line is released by clearing the interrupt flags. If TWASIE in TWSCRA is set, a STOP condition on the bus will also set TWASIF. STOP condition will set the flag only if system clock is faster than the minimum bus free time between STOP and START. Writing a one to this bit will clear the flag. This flag is also automatically cleared when writing a valid command to the TWCMDn bits in TWSCRB.
141
8263A-AVR-08/10
* Bit 5 - TWCH: TWI Clock Hold This bit is set when the slave is holding the SCL line low. This bit is read-only, and set when TWDIF or TWASIF is set. The bit can be cleared indirectly by clearing the interrupt flags and releasing the SCL line. * Bit 4 - TWRA: TWI Receive Acknowledge This bit contains the most recently received acknowledge bit from the master. This bit is read-only. When zero, the most recent acknowledge bit from the maser was ACK and, when one, the most recent acknowledge bit was NACK. * Bit 3 - TWC: TWI Collision This bit is set when the slave was not able to transfer a high data bit or a NACK bit. When a collision is detected, the slave will commence its normal operation, and disable data and acknowledge output. No low values are shifted out onto the SDA line. This bit is cleared by writing a one to it. The bit is also cleared automatically when a START or Repeated START condition is detected. * Bit 2 - TWBE: TWI Bus Error This bit is set when an illegal bus condition has occured during a transfer. An illegal bus condition occurs if a Repeated START or STOP condition is detected, and the number of bits from the previous START condition is not a multiple of nine. This bit is cleared by writing a one to it. * Bit 1 - TWDIR: TWI Read/Write Direction This bit indicates the direction bit from the last address packet received from a master. When this bit is one, a master read operation is in progress. When the bit is zero a master write operation is in progress. * Bit 0 - TWAS: TWI Address or Stop This bit indicates why the TWASIF bit was last set. If zero, a stop condition caused TWASIF to be set. If one, address detection caused TWASIF to be set. 17.5.4 TWSA - TWI Slave Address Register
Bit 0x2A Read/Write Initial Value R/W 0 R/W 0 R/W 0 0 7 6 5 4 3 2 R/W 0 1 R/W 0 0
TWSA[7:0]
R/W R/W 0 R/W 0
TWSA
The slave address register contains the TWI slave address used by the slave address match logic to determine if a master has addressed the slave. When using 7-bit or 10-bit address recognition mode, the high seven bits of the address register (TWSA[7:1]) represent the slave address. The least significant bit (TWSA0) is used for general call address recognition. Setting TWSA0 enables general call address recognition logic. When using 10-bit addressing the address match logic only support hardware address recognition of the first byte of a 10-bit address. If TWSA[7:1] is set to "0b11110nn", 'nn' will represent bits 9 and 8 of the slave address. The next byte received is then bits 7 to 0 in the 10-bit address, but this must be handled by software.
142
ATtiny40
8263A-AVR-08/10
ATtiny40
When the address match logic detects that a valid address byte has been received, the TWASIF is set and the TWDIR flag is updated. If TWPME in TWSCRA is set, the address match logic responds to all addresses transmitted on the TWI bus. TWSA is not used in this mode. 17.5.5 TWSD - TWI Slave Data Register
Bit 0x28 Read/Write Initial Value R/W 0 R/W 0 R/W 0 0 7 6 5 4 3 2 R/W 0 1 R/W 0 0
TWSD[7:0]
R/W R/W 0 R/W 0
TWSD
The data register is used when transmitting and received data. During transfer, data is shifted from/to the TWSD register and to/from the bus. Therefore, the data register cannot be accessed during byte transfers. This is protected in hardware. The data register can only be accessed when the SCL line is held low by the slave, i.e. when TWCH is set. When a master reads data from a slave, the data to be sent must be written to the TWSD register. The byte transfer is started when the master starts to clock the data byte from the slave. It is followed by the slave receiving the acknowledge bit from the master. The TWDIF and the TWCH bits are then set. When a master writes data to a slave, the TWDIF and the TWCH flags are set when one byte has been received in the data register. If Smart Mode is enabled, reading the data register will trigger the bus operation, as set by the TWAA bit in TWSCRB. Accessing TWSD will clear the slave interrupt flags and the TWCH bit. 17.5.6 TWSAM - TWI Slave Address Mask Register
Bit 0x29 Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 R/W 0 2 R/W 0 1 R/W 0 0
TWSAM[7:0]
R/W 0
TWAE
R/W 0
TWSAM
* Bits 7:1 - TWSAM[7:1]: TWI Address Mask These bits can act as a second address match register, or an address mask register, depending on the TWAE setting. If TWAE is set to zero, TWSAM can be loaded with a 7-bit slave address mask. Each bit in TWSAM can mask (disable) the corresponding address bit in the TWSA register. If the mask bit is one the address match between the incoming address bit and the corresponding bit in TWSA is ignored. In other words, masked bits will always match. If TWAE is set to one, TWSAM can be loaded with a second slave address in addition to the TWSA register. In this mode, the slave will match on 2 unique addresses, one in TWSA and the other in TWSAM. * Bit 0 - TWAE: TWI Address Enable By default, this bit is zero and the TWSAM bits acts as an address mask to the TWSA register. If this bit is set to one, the slave address match logic responds to the two unique addresses in TWSA and TWSAM.
143
8263A-AVR-08/10
18. Touch Sensing
ATtiny40 is optimized for QTouch(R) Library. QTouch(R) Library is a royalty free software library for developing touch applications on standard Atmel AVR(R) Microcontrollers.
144
ATtiny40
8263A-AVR-08/10
ATtiny40
19. Programming Interface
19.1 Features
* Physical Layer:
- Synchronous Data Transfer - Bi-directional, Half-duplex Receiver And Transmitter - Fixed Frame Format With One Start Bit, 8 Data Bits, One Parity Bit And 2 Stop Bits - Parity Error Detection, Frame Error Detection And Break Character Detection - Parity Generation And Collision Detection - Automatic Guard Time Insertion Between Data Reception And Transmission * Access Layer: - Communication Based On Messages - Automatic Exception Handling Mechanism - Compact Instruction Set - NVM Programming Access Control - Tiny Programming Interface Control And Status Space Access Control - Data Space Access Control
19.2
Overview
The Tiny Programming Interface (TPI) supports external programming of all Non-Volatile Memories (NVM). Memory programming is done via the NVM Controller, by executing NVM controller commands as described in "Memory Programming" on page 156. The Tiny Programming Interface (TPI) provides access to the programming facilities. The interface consists of two layers: the access layer and the physical layer. The layers are illustrated in Figure 19-1. Figure 19-1. The Tiny Programming Interface and Related Internal Interfaces
TINY PROGRAMMING INTERFACE (TPI) RESET TPICLK TPIDATA PHYSICAL LAYER ACCESS LAYER
NVM CONTROLLER
NON-VOLATILE MEMORIES
DATA BUS
Programming is done via the physical interface. This is a 3-pin interface, which uses the RESET pin as enable, the TPICLK pin as the clock input, and the TPIDATA pin as data input and output. NVM can be programmed at 5V, only.
19.3
Physical Layer of Tiny Programming Interface
The TPI physical layer handles the basic low-level serial communication. The TPI physical layer uses a bi-directional, half-duplex serial receiver and transmitter. The physical layer includes serial-to-parallel and parallel-to-serial data conversion, start-of-frame detection, frame error detection, parity error detection, parity generation and collision detection.
145
8263A-AVR-08/10
The TPI is accessed via three pins, as follows: RESET: TPICLK: TPIDATA: Tiny Programming Interface enable input Tiny Programming Interface clock input Tiny Programming Interface data input/output
In addition, the VCC and GND pins must be connected between the external programmer and the device. 19.3.1 Enabling The following sequence enables the Tiny Programming Interface: * Apply 5V between VCC and GND * Depending on the method of reset to be used: - Either: wait tTOUT (see Table 21-4 on page 168) and then set the RESET pin low. This will reset the device and enable the TPI physical layer. The RESET pin must then be kept low for the entire programming session - Or: if the RSTDISBL configuration bit has been programmed, apply 12V to the RESET pin. The RESET pin must be kept at 12V for the entire programming session * Wait tRST (see Table 21-4 on page 168) * Keep the TPIDATA pin high for 16 TPICLK cycles See Figure 19-2 for guidance. Figure 19-2. Sequence for enabling the Tiny Programming Interface
t
RST
16 x TPICLK CYCLES
RESET
TPICLK
TPIDATA
19.3.2
Disabling Provided that the NVM enable bit has been cleared, the TPI is automatically disabled if the RESET pin is released to inactive high state or, alternatively, if VHV is no longer applied to the RESET pin. If the NVM enable bit is not cleared a power down is required to exit TPI programming mode. See NVMEN bit in "TPISR - Tiny Programming Interface Status Register" on page 155.
19.3.3
Frame Format The TPI physical layer supports a fixed frame format. A frame consists of one character, eight bits in length, and one start bit, a parity bit and two stop bits. Data is transferred with the least significant bit first.
146
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 19-3. Serial frame format.
TPICLK
TPIDATA
IDLE
ST
D0
D1
D7
P
SP1
SP2
IDLE/ST
Symbols used in Figure 19-3: ST: D0-D7: P: SP1: SP2: 19.3.4 Start bit (always low) Data bits (least significant bit sent first) Parity bit (using even parity) Stop bit 1 (always high) Stop bit 2 (always high)
Parity Bit Calculation The parity bit is always calculated using even parity. The value of the bit is calculated by doing an exclusive-or of all the data bits, as follows: P = D0 D1 D2 D3 D4 D5 D6 D7 0 where: P: D0-D7: Parity bit using even parity Data bits of the character
19.3.5
Supported Characters The BREAK character is equal to a 12 bit long low level. It can be extended beyond a bit-length of 12. The IDLE character is equal to a 12 bit long high level. It can be extended beyond a bit-length of 12. Figure 19-4. Supported characters.
DATA CHARACTER TPIDATA IDLE ST D0 D1 D7 BREAK CHARACTER TPIDATA IDLE IDLE CHARACTER TPIDATA IDLE IDLE/ST IDLE/ST P SP1 SP2 IDLE/ST
19.3.6
Operation The TPI physical layer operates synchronously on the TPICLK provided by the external programmer. The dependency between the clock edges and data sampling or data change is shown in Figure 19-5. Data is changed at falling edges and sampled at rising edges.
147
8263A-AVR-08/10
Figure 19-5. Data changing and Data sampling.
TPICLK
TPIDATA
SAMPLE SETUP
The TPI physical layer supports two modes of operation: Transmit and Receive. By default, the layer is in Receive mode, waiting for a start bit. The mode of operation is controlled by the access layer. 19.3.7 Serial Data Reception When the TPI physical layer is in receive mode, data reception is started as soon as a start bit has been detected. Each bit that follows the start bit will be sampled at the rising edge of the TPICLK and shifted into the shift register until the second stop bit has been received. When the complete frame is present in the shift register the received data will be available for the TPI access layer. There are three possible exceptions in the receive mode: frame error, parity error and break detection. All these exceptions are signalized to the TPI access layer, which then enters the error state and puts the TPI physical layer into receive mode, waiting for a BREAK character. * Frame Error Exception. The frame error exception indicates the state of the stop bit. The frame error exception is set if the stop bit was read as zero. * Parity Error Exception. The parity of the data bits is calculated during the frame reception. After the frame is received completely, the result is compared with the parity bit of the frame. If the comparison fails the parity error exception is signalized. * Break Detection Exception. The Break detection exception is given when a complete frame of all zeros has been received. 19.3.8 Serial Data Transmission When the TPI physical layer is ready to send a new frame it initiates data transmission by loading the shift register with the data to be transmitted. When the shift register has been loaded with new data, the transmitter shifts one complete frame out on the TPIDATA line at the transfer rate given by TPICLK. If a collision is detected during transmission, the output driver is disabled. The TPI access layer enters the error state and the TPI physical layer is put into receive mode, waiting for a BREAK character. 19.3.9 Collision Detection Exception The TPI physical layer uses one bi-directional data line for both data reception and transmission. A possible drive contention may occur, if the external programmer and the TPI physical layer drive the TPIDATA line simultaneously. In order to reduce the effect of the drive contention, a collision detection mechanism is supported. The collision detection is based on the way the TPI physical layer drives the TPIDATA line.
148
ATtiny40
8263A-AVR-08/10
ATtiny40
The TPIDATA line is driven by a tri-state, push-pull driver with internal pull-up. The output driver is always enabled when a logical zero is sent. When sending successive logical ones, the output is only driven actively during the first clock cycle. After this, the output driver is automatically tristated and the TPIDATA line is kept high by the internal pull-up. The output is re-enabled, when the next logical zero is sent. The collision detection is enabled in transmit mode, when the output driver has been disabled. The data line should now be kept high by the internal pull-up and it is monitored to see, if it is driven low by the external programmer. If the output is read low, a collision has been detected. There are some potential pit-falls related to the way collision detection is performed. For example, collisions cannot be detected when the TPI physical layer transmits a bit-stream of successive logical zeros, or bit-stream of alternating logical ones and zeros. This is because the output driver is active all the time, preventing polling of the TPIDATA line. However, within a single frame the two stop bits should always be transmitted as logical ones, enabling collision detection at least once per frame (as long as the frame format is not violated regarding the stop bits). The TPI physical layer will cease transmission when it detects a collision on the TPIDATA line. The collision is signalized to the TPI access layer, which immediately changes the physical layer to receive mode and goes to the error state. The TPI access layer can be recovered from the error state only by sending a BREAK character. 19.3.10 Direction Change In order to ensure correct timing of the half-duplex operation, a simple guard time mechanism has been added to the physical layer. When the TPI physical layer changes from receive to transmit mode, a configurable number of additional IDLE bits are inserted before the start bit is transmitted. The minimum transition time between receive and transmit mode is two IDLE bits. The total IDLE time is the specified guard time plus two IDLE bits. The guard time is configured by dedicated bits in the TPIPCR register. The default guard time value after the physical layer is initialized is 128 bits. The external programmer looses control of the TPIDATA line when the TPI target changes from receive mode to transmit. The guard time feature relaxes this critical phase of the communication. When the external programmer changes from receive mode to transmit, a minimum of one IDLE bit should be inserted before the start bit is transmitted.
19.4
Access Layer of Tiny Programming Interface
The TPI access layer is responsible for handling the communication with the external programmer. The communication is based on a message format, where each message comprises an instruction followed by one or more byte-sized operands. The instruction is always sent by the external programmer but operands are sent either by the external programmer or by the TPI access layer, depending on the type of instruction issued. The TPI access layer controls the character transfer direction on the TPI physical layer. It also handles the recovery from the error state after exception. The Control and Status Space (CSS) of the Tiny Programming Interface is allocated for control and status registers in the TPI access Layer. The CSS consist of registers directly involved in the operation of the TPI itself. These register are accessible using the SLDCS and SSTCS instructions.
149
8263A-AVR-08/10
The access layer can also access the data space, either directly or indirectly using the Pointer Register (PR) as the address pointer. The data space is accessible using the SLD, SST, SIN and SOUT instructions. The address pointer can be stored in the Pointer Register using the SLDPR instruction. 19.4.1 Message format Each message comprises an instruction followed by one or more byte operands. The instruction is always sent by the external programmer. Depending on the instruction all the following operands are sent either by the external programmer or by the TPI. The messages can be categorized in two types based on the instruction, as follows: * Write messages. A write message is a request to write data. The write message is sent entirely by the external programmer. This message type is used with the SSTCS, SST, STPR, SOUT and SKEY instructions. * Read messages. A read message is a request to read data. The TPI reacts to the request by sending the byte operands. This message type is used with the SLDCS, SLD and SIN instructions. All the instructions except the SKEY instruction require the instruction to be followed by one byte operand. The SKEY instruction requires 8 byte operands. For more information, see the TPI instruction set on page 150. 19.4.2 Exception Handling and Synchronisation Several situations are considered exceptions from normal operation of the TPI. When the TPI physical layer is in receive mode, these exceptions are: * The TPI physical layer detects a parity error. * The TPI physical layer detects a frame error. * The TPI physical layer recognizes a BREAK character. When the TPI physical layer is in transmit mode, the possible exceptions are: * The TPI physical layer detects a data collision. All these exceptions are signalized to the TPI access layer. The access layer responds to an exception by aborting any on-going operation and enters the error state. The access layer will stay in the error state until a BREAK character has been received, after which it is taken back to its default state. As a consequence, the external programmer can always synchronize the protocol by simply transmitting two successive BREAK characters.
19.5
Instruction Set
The TPI has a compact instruction set that is used to access the TPI Control and Status Space (CSS) and the data space. The instructions allow the external programmer to access the TPI, the NVM Controller and the NVM memories. All instructions except SKEY require one byte operand following the instruction. The SKEY instruction is followed by 8 data bytes. All instructions are byte-sized.
150
ATtiny40
8263A-AVR-08/10
ATtiny40
The TPI instruction set is summarised in Table 19-1. Table 19-1.
Mnemonic SLD SLD SST SST SSTPR SIN SOUT SLDCS SSTCS SKEY
Instruction Set Summary
Operand data, PR data, PR+ PR, data PR+, data PR, a data, a a, data data, a a, data Key, {8{data}} Description Serial LoaD from data space using indirect addressing Serial LoaD from data space using indirect addressing and post-increment Serial STore to data space using indirect addressing Serial STore to data space using indirect addressing and post-increment Serial STore to Pointer Register using direct addressing Serial IN from data space Serial OUT to data space Serial LoaD from Control and Status space using direct addressing Serial STore to Control and Status space using direct addressing Serial KEY Operation data DS[PR] data DS[PR] PR PR+1 DS[PR] data DS[PR] data PR PR+1 PR[a] data data I/O[a] I/O[a] data data CSS[a] CSS[a] data Key {8{data}}
19.5.1
SLD - Serial LoaD from data space using indirect addressing The SLD instruction uses indirect addressing to load data from the data space to the TPI physical layer shift-register for serial read-out. The data space location is pointed by the Pointer Register (PR), where the address must have been stored before data is accessed. The Pointer Register can either be left unchanged by the operation, or it can be post-incremented, as shown in Table 19-2. Table 19-2.
Operation
The Serial Load from Data Space (SLD) Instruction
Opcode Remarks Register
data DS[PR] data DS[PR] 19.5.2
0010 0000 0010 0100
PR PR PR PR + 1
Unchanged Post increment
SST - Serial STore to data space using indirect addressing The SST instruction uses indirect addressing to store into data space the byte that is shifted into the physical layer shift register. The data space location is pointed by the Pointer Register (PR), where the address must have been stored before the operation. The Pointer Register can be either left unchanged by the operation, or it can be post-incremented, as shown in Table 19-3. Table 19-3.
Operation
The Serial Store to Data Space (SLD) Instruction
Opcode Remarks Register
DS[PR] data DS[PR] data
0110 0000 0110 0100
PR PR PR PR + 1
Unchanged Post increment
151
8263A-AVR-08/10
19.5.3
SSTPR - Serial STore to Pointer Register The SSTPR instruction stores the data byte that is shifted into the physical layer shift register to the Pointer Register (PR). The address bit of the instruction specifies which byte of the Pointer Register is accessed, as shown in Table 19-4. Table 19-4.
Operation
The Serial Store to Pointer Register (SSTPR) Instruction
Opcode Remarks
PR[a] data 19.5.4
0110 100a
Bit `a' addresses Pointer Register byte
SIN - Serial IN from i/o space using direct addressing The SIN instruction loads data byte from the I/O space to the shift register of the physical layer for serial read-out. The instuction uses direct addressing, the address consisting of the 6 address bits of the instruction, as shown in Table 19-5. Table 19-5.
Operation
The Serial IN from i/o space (SIN) Instruction
Opcode Remarks
data I/O[a] 19.5.5
0aa1 aaaa
Bits marked `a' form the direct, 6-bit addres
SOUT - Serial OUT to i/o space using direct addressing The SOUT instruction stores the data byte that is shifted into the physical layer shift register to the I/O space. The instruction uses direct addressing, the address consisting of the 6 address bits of the instruction, as shown in Table 19-6. Table 19-6.
Operation
The Serial OUT to i/o space (SOUT) Instruction
Opcode Remarks
I/O[a] data 19.5.6
1aa1 aaaa
Bits marked `a' form the direct, 6-bit addres
SLDCS - Serial LoaD data from Control and Status space using direct addressing The SLDCS instruction loads data byte from the TPI Control and Status Space to the TPI physical layer shift register for serial read-out. The SLDCS instruction uses direct addressing, the direct address consisting of the 4 address bits of the instruction, as shown in Table 19-7. Table 19-7.
Operation
The Serial Load Data from Control and Status space (SLDCS) Instruction
Opcode Remarks
data CSS[a] 19.5.7
1000 aaaa
Bits marked `a' form the direct, 4-bit addres
SSTCS - Serial STore data to Control and Status space using direct addressing The SSTCS instruction stores the data byte that is shifted into the TPI physical layer shift register to the TPI Control and Status Space. The SSTCS instruction uses direct addressing, the direct address consisting of the 4 address bits of the instruction, as shown in Table 19-8. Table 19-8.
Operation
The Serial STore data to Control and Status space (SSTCS) Instruction
Opcode Remarks
CSS[a] data
1100 aaaa
Bits marked `a' form the direct, 4-bit addres
152
ATtiny40
8263A-AVR-08/10
ATtiny40
19.5.8 SKEY - Serial KEY signaling The SKEY instruction is used to signal the activation key that enables NVM programming. The SKEY instruction is followed by the 8 data bytes that includes the activation key, as shown in Table 19-9. Table 19-9.
Operation
The Serial KEY signaling (SKEY) Instruction
Opcode Remarks
Key {8[data}}
1110 0000
Data bytes follow after instruction
19.6
Accessing the Non-Volatile Memory Controller
By default, NVM programming is not enabled. In order to access the NVM Controller and be able to program the non-volatile memories, a unique key must be sent using the SKEY instruction. The 64-bit key that will enable NVM programming is given in Table 19-10. Table 19-10. Enable Key for Non-Volatile Memory Programming
Key NVM Program Enable Value
0x1289AB45CDD888FF
After the key has been given, the Non-Volatile Memory Enable (NVMEN) bit in the TPI Status Register (TPISR) must be polled until the Non-Volatile memory has been enabled. NVM programming is disabled by writing a logical zero to the NVMEN bit in TPISR.
19.7
Control and Status Space Register Descriptions
The control and status registers of the Tiny Programming Interface are mapped in the Control and Status Space (CSS) of the interface. These registers are not part of the I/O register map and are accessible via SLDCS and SSTCS instructions, only. The control and status registers are directly involved in configuration and status monitoring of the TPI. A summary of CSS registers is shown in Table 19-11. Table 19-11. Summary of Control and Status Registers
Addr. 0x0F 0x0E 0x0D 0x0C 0x0B 0x0A 0x09 0x08 0x07 0x06 0x05 0x04 0x03 Name TPIIR Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved - - - - - - - - - - - - - - - - - - - - - - - - Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Tiny Programming Interface Identification Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153
8263A-AVR-08/10
Table 19-11. Summary of Control and Status Registers
Addr. 0x02 0x01 0x00 Name TPIPCR Reserved TPISR Bit 7 - - - Bit 6 - - - Bit 5 - - - Bit 4 - - - Bit 3 - - - Bit 2 GT2 - - Bit 1 GT1 - NVMEN Bit 0 GT0 - -
19.7.1
TPIIR - Tiny Programming Interface Identification Register
Bit CSS: 0x0F Read/Write Initial Value R 0 R 0 7 6 5 R 0 4 R 0 3 R 0 2 R 0 1 R 0 0
Programming Interface Identification Code
R 0
TPIIR
* Bits 7:0 - TPIIC: Tiny Programming Interface Identification Code These bits give the identification code for the Tiny Programming Interface. The code can be used be the external programmer to identify the TPI. The identification code of the Tiny Programming Interface is shown in Table 19-12. Table 19-12. Identification Code for Tiny Programming Interface
Code Interface Identification Value
0x80
19.7.2
TPIPCR - Tiny Programming Interface Physical Layer Control Register
Bit CSS: 0x02 Read/Write Initial Value 7 6 5 4 3 2 1 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
GT2
R/W 0
GT1
R/W 0
GT0
R/W 0
TPIPCR
* Bits 7:3 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 2:0 - GT[2:0]: Guard Time These bits specify the number of additional IDLE bits that are inserted to the idle time when changing from reception mode to transmission mode. Additional delays are not inserted when changing from transmission mode to reception. The total idle time when changing from reception to transmission mode is Guard Time plus two IDLE bits. Table 19-13 shows the available Guard Time settings. Table 19-13. Guard Time Settings
GT2 0 0 0 0 1 GT1 0 0 1 1 0 GT0 0 1 0 1 0 Guard Time (Number of IDLE bits) +128 (default value) +64 +32 +16 +8
154
ATtiny40
8263A-AVR-08/10
ATtiny40
Table 19-13. Guard Time Settings
GT2 1 1 1 GT1 0 1 1 GT0 1 0 1 Guard Time (Number of IDLE bits) +4 +2 +0
The default Guard Time is 128 IDLE bits. To speed up the communication, the Guard Time should be set to the shortest safe value. 19.7.3 TPISR - Tiny Programming Interface Status Register
Bit CSS: 0x00 Read/Write Initial Value 7 6 5 4 3 2 1 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
NVMEN
R/W 0
-
R 0
TPISR
* Bits 7:2, 0 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bit 1 - NVMEN: Non-Volatile Memory Programming Enabled NVM programming is enabled when this bit is set. The external programmer can poll this bit to verify the interface has been successfully enabled. NVM programming is disabled by writing this bit to zero.
155
8263A-AVR-08/10
20. Memory Programming
20.1 Features
* Two Embedded Non-Volatile Memories:
- Non-Volatile Memory Lock bits (NVM Lock bits) - Flash Memory Four Separate Sections Inside Flash Memory: - Code Section (Program Memory) - Signature Section - Configuration Section - Calibration Section Read Access to All Non-Volatile Memories from Application Software Read and Write Access to Non-Volatile Memories from External programmer: - Read Access to All Non-Volatile Memories - Write Access to NVM Lock Bits, Flash Code Section and Flash Configuration Section External Programming: - Support for In-System and Mass Production Programming - Programming Through the Tiny Programming Interface (TPI) High Security with NVM Lock Bits
*
* *
*
*
20.2
Overview
The Non-Volatile Memory (NVM) Controller manages all access to the Non-Volatile Memories. The NVM Controller controls all NVM timing and access privileges, and holds the status of the NVM. During normal execution the CPU will execute code from the code section of the Flash memory (program memory). When entering sleep and no programming operations are active, the Flash memory is disabled to minimize power consumption. All NVM are mapped to the data memory. Application software can read the NVM from the mapped locations of data memory using load instruction with indirect addressing. The NVM has only one read port and, therefore, the next instruction and the data can not be read simultaneously. When the application reads data from NVM locations mapped to the data space, the data is read first before the next instruction is fetched. The CPU execution is here delayed by one system clock cycle. Internal programming operations to NVM have been disabled and the NVM therefore appears to the application software as read-only. Internal write or erase operations of the NVM will not be successful. The method used by the external programmer for writing the Non-Volatile Memories is referred to as external programming. External programming can be done both in-system or in mass production. The external programmer can read and program the NVM via the Tiny Programming Interface (TPI). In the external programming mode all NVM can be read and programmed, except the signature and the calibration sections which are read-only. NVM can be programmed at 5V, only.
156
ATtiny40
8263A-AVR-08/10
ATtiny40
20.3 Non-Volatile Memories
The ATtiny40 has the following, embedded NVM: * Non-Volatile Memory Lock Bits * Flash memory with four separate sections
20.3.1
Non-Volatile Memory Lock Bits The ATtiny40 provides two Lock Bits, as shown in Table 20-1. Table 20-1.
Lock Bit
Lock Bit Byte
Bit No 7 6 5 4 3 2 Description Default Value 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) Non-Volatile Lock Bit Non-Volatile Lock Bit 1 (unprogrammed) 1 (unprogrammed)
NVLB2 NVLB1
1 0
The Lock Bits can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional security shown in Table 20-2. Lock Bits can be erased to "1" with the Chip Erase command, only. Table 20-2.
Lock Mode 1
Lock Bit Protection Modes
NVLB2 (2) 1 NVLB1 (2) 1 Protection Type No Memory Lock feature Enabled Further Programming of the Flash memory is disabled in the external programming mode. The configuration section bits are locked in the external programming mode Further programming and verification of the flash is disabled in the external programming mode. The configuration section bits are locked in the external programming mode
Memory Lock Bits (1)
2
1
0
3
0
0
Notes:
1. Program the configuration section bits before programming NVLB1 and NVLB2. 2. "1" means unprogrammed, "0" means programmed
157
8263A-AVR-08/10
20.3.2
Flash Memory The embedded Flash memory of ATtiny40 has four separate sections, as shown in Table 20-3. Table 20-3.
Section Code (program memory) Configuration Signature
(1)
Number of Words and Pages in the Flash
Size (Bytes) 4096 32 32 32 Page Size (Words) 32 32 16 32 Pages 64 1 2 1 WADDR [5:1] [5:1] [4:1] [5:1] PADDR [11:6] - [5:5] -
Calibration (1) Notes:
1. This section is read-only.
20.3.3
Configuration Section ATtiny40 has one configuration byte, which resides in the configuration section. See Table 20-4. Table 20-4. Configuration bytes
Configuration word data Configuration word address 0x00 0x01 ... 0x1F High byte Reserved Reserved Low byte Configuration Byte 0 Reserved
Table 20-5 briefly describes the functionality of all configuration bits and how they are mapped into the configuration byte. Table 20-5.
Bit 7 6 5 4 3 2 1 0 Notes: - BODLEVEL2
(1)
Configuration Byte 0
Bit Name Description Reserved Brown-out Detector trigger level Brown-out Detector trigger level Brown-out Detector trigger level Reserved System Clock Output Watchdog Timer always on External Reset disable Default Value 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed)
BODLEVEL1(1) BODLEVEL0(1) - CKOUT WDTON RSTDISBL
1. See Table 21-6 on page 168 for BODLEVEL Fuse decoding.
Configuration bits are not affected by a chip erase but they can be cleared using the configuration section erase command (see "Erasing the Configuration Section" on page 162). Note that configuration bits are locked if Non-Volatile Lock Bit 1 (NVLB1) is programmed.
158
ATtiny40
8263A-AVR-08/10
ATtiny40
20.3.3.1 Latching of Configuration Bits All configuration bits are latched either when the device is reset or when the device exits the external programming mode. Changes to configuration bit values have no effect until the device leaves the external programming mode. Signature Section The signature section is a dedicated memory area used for storing miscellaneous device information, such as the device signature. Most of this memory section is reserved for internal use, as shown in Table 20-6. Table 20-6. Signature bytes
Signature word data Signature word address 0x00 0x01 0x02 ... 0x3F High byte Device ID 1 Reserved for internal use Reserved for internal use Low byte Manufacturer ID Device ID 2 Reserved for internal use
20.3.4
ATtiny40 has a three-byte signature code, which can be used to identify the device. The three bytes reside in the signature section, as shown in Table 20-6. The signature data for ATtiny40 is given in Table 20-7. Table 20-7.
Part
Signature codes
Signature Bytes Manufacturer ID 0x1E Device ID 1 0x92 Device ID 2 0x0E
ATtiny40
20.3.5
Calibration Section ATtiny40 has one calibration byte. The calibration byte contains the calibration data for the internal oscillator and resides in the calibration section, as shown in Table 20-8. During reset, the calibration byte is automatically written into the OSCCAL register to ensure correct frequency of the calibrated internal oscillator. Table 20-8. Calibration byte
Calibration word data Calibration word address 0x00 0x01 ... 0x1F High byte Reserved Reserved Low byte Internal oscillator calibration value Reserved
20.3.5.1
Latching of Calibration Value To ensure correct frequency of the calibrated internal oscillator the calibration value is automatically written into the OSCCAL register during reset.
159
8263A-AVR-08/10
20.4
Accessing the NVM
NVM lock bits, and all Flash memory sections are mapped to the data space as shown in Figure 5-1 on page 16. The NVM can be accessed for read and programming via the locations mapped in the data space. The NVM Controller recognises a set of commands that can be used to instruct the controller what type of programming task to perform on the NVM. Commands to the NVM Controller are issued via the NVM Command Register. See "NVMCMD - Non-Volatile Memory Command Register" on page 164. After the selected command has been loaded, the operation is started by writing data to the NVM locations mapped to the data space. When the NVM Controller is busy performing an operation it will signal this via the NVM Busy Flag in the NVM Control and Status Register. See "NVMCSR - Non-Volatile Memory Control and Status Register" on page 164. The NVM Command Register is blocked for write access as long as the busy flag is active. This is to ensure that the current command is fully executed before a new command can start. Programming any part of the NVM will automatically inhibit the following operations: * All programming to any other part of the NVM * All reading from any NVM location The ATtiny40 supports only external programming. Internal programming operations to the NVM have been disabled, which means any internal attempt to write or erase NVM locations will fail.
20.4.1
Addressing the Flash The data space uses byte accessing but since the Flash sections are accessed as words and organized in pages, the byte-address of the data space must be converted to the word-address of the Flash section. This is illustrated in Figure 20-1. Also, see Table 20-3 on page 158. Figure 20-1. Addressing the Flash Memory
16 PADDRMSB WADDRMSB+1 WADDRMSB 1
PADDR
ADDRESS POINTER
WADDR
0/1
LOW/HIGH BYTE SELECT
FLASH SECTION
00 01 02 ... ... ... 00 01 ...
FLASH PAGE
WORD
WORD ADDRESS WITHIN A FLASH PAGE
PAGE
PAGE ADDRESS WITHIN A FLASH SECTION
... ...
PAGEEND SECTIONEND
160
ATtiny40
8263A-AVR-08/10
ATtiny40
The most significant bits of the data space address select the NVM Lock bits or the Flash section mapped to the data memory. The word address within a page (WADDR) is held by the bits [WADDRMSB:1], and the page address (PADDR) is held by the bits [PADDRMSB:WADDRMSB+1]. Together, PADDR and WADDR form the absolute address of a word in the Flash section. The least significant bit of the Flash section address is used to select the low or high byte of the word. 20.4.2 Reading the Flash The Flash can be read from the data memory mapped locations one byte at a time. For read operations, the least significant bit (bit 0) is used to select the low or high byte in the word address. If this bit is zero, the low byte is read, and if it is one, the high byte is read. Programming the Flash The Flash can be written four words at a time. Before writing a Flash words, the Flash target location must be erased. Writing to an un-erased Flash word will corrupt its content. The Flash is written four words at a time but the data space uses byte-addressing to access Flash that has been mapped to data memory. It is therefore important to write the four words in the correct order to the Flash, namely low bytes before high bytes. The low byte of the first word is first written to the temporary buffer, then the high byte. Writing the low byte and then the high byte to the buffer latches the four words into the Flash write buffer, starting the actual Flash write operation. The Flash erase operations can only performed for the entire Flash sections. The Flash programming sequence is as follows: 1. Perform a Flash section erase or perform a Chip erase 2. Write the Flash section four words at a time
20.4.3
20.4.3.1
Chip Erase The Chip Erase command will erase the entire code section of the Flash memory and the NVM Lock Bits. For security reasons, however, the NVM Lock Bits are not reset before the code section has been completely erased. The Configuration, Signature and Calibration sections are not changed. Before starting the Chip erase, the NVMCMD register must be loaded with the CHIP_ERASE command. To start the erase operation a dummy byte must be written into the high byte of a word location that resides inside the Flash code section. The NVMBSY bit remains set until erasing has been completed. While the Flash is being erased neither Flash buffer loading nor Flash reading can be performed. The Chip Erase can be carried out as follows: 1. Write the CHIP_ERASE command to the NVMCMD register 2. Start the erase operation by writing a dummy byte to the high byte of any word location inside the code section 3. Wait until the NVMBSY bit has been cleared
161
8263A-AVR-08/10
20.4.3.2
Erasing the Code Section The algorithm for erasing all pages of the Flash code section is as follows: 1. Write the SECTION_ERASE command to the NVMCMD register 2. Start the erase operation by writing a dummy byte to the high byte of any word location inside the code section 3. Wait until the NVMBSY bit has been cleared
20.4.3.3
Writing Flash Code Words The algorithm for writing four words to the code section is as follows: 1. Write the CODE_WRITE command to the NVMCMD register 2. Write the low byte of the 1st word to the low byte of a target word location 3. Write the high byte of the 1st word to the high byte of the same target word location 4. Send IDLE character as described in section "Supported Characters" on page 147 5. Write the low byte of the 2nd word to the low byte of the next target word location 6. Write the high byte of the 2nd word to the high byte of the same target word location. 7. Send IDLE character as described in section "Supported Characters" on page 147 8. Write the low byte of the 3rd word to the low byte of a target word location 9. Write the high byte of the 3rd word to the high byte of the same target word location 10. Send IDLE character as described in section "Supported Characters" on page 147 11. Write the low byte of the 4th word to the low byte of the next target word location 12. Write the high byte of the 4th word to the high byte of the same target word location. This will start the Flash write operation 13. Wait until the NVMBSY bit has been cleared
20.4.3.4
Erasing the Configuration Section The algorithm for erasing the Configuration section is as follows: 1. Write the SECTION_ERASE command to the NVMCMD register 2. Start the erase operation by writing a dummy byte to the high byte of any word location inside the configuration section 3. Wait until the NVMBSY bit has been cleared
20.4.3.5
Writing a Configuration Word The algorithm for writing a Configuration word is as follows. 1. Write the CODE_WRITE command to the NVMCMD register 2. Write the low byte of the data word to the low byte of the configuration word location 3. Write the high byte of the data word to the high byte of the same configuration word location 4. Send IDLE character as described in section "Supported Characters" on page 147 5. Write a dummy byte to the low byte of the next configuration word location 6. Write a dummy byte to the high byte of the same configuration word location. 7. Send IDLE character as described in section "Supported Characters" on page 147
162
ATtiny40
8263A-AVR-08/10
ATtiny40
8. Write a dummy byte to the low byte of the next configuration word location 9. Write a dummy byte to the high byte of the same configuration word location. 10. Send IDLE character as described in section "Supported Characters" on page 147 11. Write a dummy byte to the low byte of the next configuration word location 12. Write a dummy byte to the high byte of the same configuration word location. This will start the Flash write operation 13. Wait until the NVMBSY bit has been cleared
20.4.4
Reading NVM Lock Bits The Non-Volatile Memory Lock Byte can be read from the mapped location in data memory. Writing NVM Lock Bits The algorithm for writing the Lock bits is as follows. 1. Write the CODE_WRITE command to the NVMCMD register. 2. Write the lock bits value to the Non-Volatile Memory Lock Byte location. This is the low byte of the Non-Volatile Memory Lock Word. 3. Start the NVM Lock Bit write operation by writing a dummy byte to the high byte of the NVM Lock Word location. 4. Wait until the NVMBSY bit has been cleared.
20.4.5
20.5 20.6
Self programming
The ATtiny40 doesn't support internal programming.
External Programming
The method for programming the Non-Volatile Memories by means of an external programmer is referred to as external programming. External programming can be done both in-system or in mass production. The Non-Volatile Memories can be externally programmed via the Tiny Programming Interface (TPI). For details on the TPI, see "Programming Interface" on page 145. Using the TPI, the external programmer can access the NVM control and status registers mapped to I/O space and the NVM memory mapped to data memory space.
20.6.1
Entering External Programming Mode The TPI must be enabled before external programming mode can be entered. The following procedure describes, how to enter the external programming mode after the TPI has been enabled: 1. Make a request for enabling NVM programming by sending the NVM memory access key with the SKEY instruction. 2. Poll the status of the NVMEN bit in TPISR until it has been set. Refer to the Tiny Programming Interface description on page 145 for more detailed information of enabling the TPI and programming the NVM.
20.6.2
Exiting External Programming Mode Clear the NVM enable bit to disable NVM programming, then release the RESET pin.
163
8263A-AVR-08/10
See NVMEN bit in "TPISR - Tiny Programming Interface Status Register" on page 155.
20.7
20.7.1
Register Description
NVMCMD - Non-Volatile Memory Command Register
Bit 0x33 Read/Write Initial Value 7 6 5 R/W 0 4 R/W 0 3 R/W 0 2 R/W 0 1 R/W 0 0
-
R 0
-
R 0
NVMCMD[5:0]
R/W 0
NVMCMD
* Bits 7:6 - Res: Reserved Bits These bits are reserved and will always read as zero. * Bits 5:0 - NVMCMD[5:0]: Non-Volatile Memory Command These bits define the programming commands for the flash, as shown in Table 20-9. Table 20-9. NVM Programming commands
NVMCMD Operation Type General Section Flash Words Binary 0b000000 0b010000 0b010100 0b011101 Hex 0x00 0x10 0x14 0x1D Mnemonic NO_OPERATION CHIP_ERASE SECTION_ERASE CODE_WRITE Description No operation Chip erase Section erase Write Flash words
20.7.2
NVMCSR - Non-Volatile Memory Control and Status Register
Bit 0x32 Read/Write Initial Value 7 6 5 4 3 2 1 0
NVMBSY
R/W 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
-
R 0
NVMCSR
* Bit 7 - NVMBSY: Non-Volatile Memory Busy This bit indicates the NVM memory (Flash memory and Lock Bits) is busy, being programmed. This bit is set when a program operation is started, and it remains set until the operation has been completed. * Bits 6:0 - Res: Reserved Bits These bits are reserved and will always read as zero.
164
ATtiny40
8263A-AVR-08/10
ATtiny40
21. Electrical Characteristics
21.1 Absolute Maximum Ratings*
*NOTICE: Stresses beyond those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability. Operating Temperature.................................. -55C to +125C Storage Temperature ..................................... -65C to +150C Voltage on any Pin except RESET with respect to Ground ................................-0.5V to VCC+0.5V Voltage on RESET with respect to Ground......-0.5V to +13.0V Maximum Operating Voltage ............................................ 6.0V DC Current per I/O Pin ............................................... 40.0 mA DC Current VCC and GND Pins................................ 200.0 mA
21.2
DC Characteristics
DC Characteristics. TA = -40C to +85C
Parameter Input Low Voltage Input High-voltage Except RESET pin Input High-voltage RESET pin Output Low Voltage(4) Except RESET pin(6) Output High-voltage(5) Except RESET pin(6) Input Leakage Current I/O Pin Input Leakage Current I/O Pin Reset Pull-up Resistor I/O Pin Pull-up Resistor Analog Comparator Input Leakage Current Condition VCC = 1.8V - 2.4V VCC = 2.4V - 5.5V VCC = 1.8V - 2.4V VCC = 2.4V - 5.5V VCC = 1.8V - 5.5V IOL = 10 mA, VCC = 5V IOL = 5 mA, VCC = 3V IOH = -10 mA, VCC = 5V IOH = -5 mA, VCC = 3V VCC = 5.5V, pin low (absolute value) VCC = 5.5V, pin high (absolute value) VCC = 5.5V, input low VCC = 5.5V, input low VCC = 5V Vin = VCC/2 30 20 -50 4.3 2.5 <0.05 <0.05 1 1 60 50 50 Min -0.5 0.7VCC(2) 0.6VCC(2) 0.9VCC(2) Typ(1) Max 0.2VCC 0.3VCC(3) VCC +0.5 VCC +0.5 0.6 0.5
(3)
Table 21-1.
Symbol VIL
Units V V V V V A A k k nA
VIH
VOL VOH ILIL ILIH RRST RPU IACLK
165
8263A-AVR-08/10
Table 21-1.
Symbol
DC Characteristics. TA = -40C to +85C (Continued)
Parameter Condition Active 1MHz, VCC = 2V Active 4MHz, VCC = 3V Power Supply Current(7) Active 8MHz, VCC = 5V Idle 1MHz, VCC = 2V Idle 4MHz, VCC = 3V Idle 8MHz, VCC = 5V Power-down mode(8) WDT enabled, VCC = 3V WDT disabled, VCC = 3V Min Typ(1) 0.4 1.1 3.2 0.03 0.2 0.8 4.5 0.15 Max 0.6 2 5 0.2 0.5 1.5 10 2 Units mA mA mA mA mA mA A A
ICC
Notes:
1. Typical values at 25C. 2. "Min" means the lowest value where the pin is guaranteed to be read as high. 3. "Max" means the highest value where the pin is guaranteed to be read as low. 4. Although each I/O port can sink more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state conditions (non-transient), the sum of all IOL (for all ports) should not exceed 60 mA. If IOL exceeds the test conditions, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition. 5. Although each I/O port can source more than the test conditions (10 mA at VCC = 5V, 5 mA at VCC = 3V) under steady state conditions (non-transient), the sum of all IOH (for all ports) should not exceed 60 mA. If IOH exceeds the test condition, VOH may exceed the related specification. Pins are not guaranteed to source current greater than the listed test condition. 6. The RESET pin must tolerate high voltages when entering and operating in programming modes and, as a consequence, has a weak drive strength as compared to regular I/O pins. See Figure 22-32 to Figure 22-37, starting from page 188. 7. Values are with external clock using methods described in "Minimizing Power Consumption" on page 29. Power Reduction is enabled (PRR = 0xFF) and there is no I/O drive. 8. BOD Disabled.
21.3
Speed
The maximum operating frequency of the device depends on VCC . As shown in Figure 21-1, the relationship between maximum frequency vs. VCC is linear between 1.8V - 2.7V and 2.7V - 4.5V. Figure 21-1. Maximum Frequency vs. VCC
12 MHz
8 MHz
4 MHz
1.8V
2.7V
4.5V
5.5V
166
ATtiny40
8263A-AVR-08/10
ATtiny40
21.4
21.4.1
Clock Characteristics
Accuracy of Calibrated Internal Oscillator It is possible to manually calibrate the internal oscillator to be more accurate than default factory calibration. Note that the oscillator frequency depends on temperature and voltage. Voltage and temperature characteristics can be found in Figure 22-55 on page 199 and Figure 22-56 on page 200. Calibration Accuracy of Internal RC Oscillator
Target Frequency 8.0 MHz Fixed frequency within: 7.3 - 8.1 MHz VCC 3V Fixed voltage within: 1.8V - 5.5V Temperature 25C Fixed temp. within: -40C to +85C Accuracy at given Voltage & Temperature(1) 10% 1%
Table 21-2.
Calibration Method Factory Calibration User Calibration Notes:
1. Accuracy of oscillator frequency at calibration point (fixed temperature and fixed voltage).
21.4.2
External Clock Drive Figure 21-2. External Clock Drive Waveform
V IH1 V IL1
Table 21-3.
Symbol 1/tCLCL tCLCL tCHCX tCLCX tCLCH tCHCL
External Clock Drive Characteristics
VCC = 1.8 - 5.5V Parameter Clock Frequency Clock Period High Time Low Time Rise Time Fall Time Change in period from one clock cycle to the next Min. 0 250 100 100 2.0 2.0 2 Max. 4 VCC = 2.7 - 5.5V Min. 0 125 40 40 1.6 1.6 2 Max. 8 VCC = 4.5 - 5.5V Min. 0 83 20 20 0.5 0.5 2 Max. 12 Units MHz ns ns ns s s %
tCLCL
167
8263A-AVR-08/10
21.5
System and Reset Characteristics
Table 21-4.
Symbol VRST VBG tRST tTOUT
Reset and Internal Voltage Characteristics
Parameter RESET Pin Threshold Voltage Internal bandgap voltage Minimum pulse width on RESET Pin Time-out after reset VCC = 2.7V TA = 25C VCC = 1.8V VCC = 3V VCC = 5V Condition Min 0.2 VCC 1.0 1.1 2000 700 400 64 128 Typ Max 0.9VCC 1.2 Units V V
ns ms
21.5.1
Power-On Reset Table 21-5.
Symbol VPOR VPOA SRON Note:
Characteristics of Enhanced Power-On Reset. TA = -40 to +85C
Parameter Release threshold of power-on reset (2) Activation threshold of power-on reset Power-on Slope Rate
(3)
Min(1) 1.1 0.6 0.01
Typ(1) 1.4 1.3
Max(1) 1.6 1.6
Units V V V/ms
1. Values are guidelines, only 2. Threshold where device is released from reset when voltage is rising 3. The Power-on Reset will not work unless the supply voltage has been below VPOT (falling)
21.5.2
Brown-Out Detection Table 21-6. VBOT vs. BODLEVEL Fuse Coding
Min(1) Typ(1) BOD Disabled 1.7 2.5 4.1 1.8 2.7 4.3 Reserved 2.0 2.9 4.5 V Max(1) Units 111 110 101 100 0XX Note:
BODLEVEL[2:0] Fuses
1. VBOT may be below nominal minimum operating voltage for some devices. For devices where this is the case, the device is tested down to VCC = VBOT during the production test. This guarantees that a Brown-out Reset will occur before VCC drops to a voltage where correct operation of the microcontroller is no longer guaranteed.
168
ATtiny40
8263A-AVR-08/10
ATtiny40
21.6 Analog Comparator Characteristics
Analog Comparator Characteristics, TA = -40C to +85C
Parameter Input Offset Voltage Input Leakage Current Analog Propagation Delay (from saturation to slight overdrive) tAPD Analog Propagation Delay (large step change) Digital Propagation Delay Condition VCC = 5V, VIN = VCC / 2 VCC = 5V, VIN = VCC / 2 VCC = 2.7V VCC = 4.0V VCC = 2.7V VCC = 4.0V VCC = 1.8V - 5.5 -50 750 500 100 75 1 2 CLK ns Min Typ < 10 Max 40 50 Units mV nA
Table 21-7.
Symbol VAIO ILAC
tDPD
21.7
ADC Characteristics
ADC Characteristics. T = -40C to +85C. VCC = 2.5V - 5.5V
Parameter Resolution VREF = VCC = 4V, ADC clock = 200 kHz Absolute accuracy (Including INL, DNL, and Quantization, Gain and Offset Errors) VREF = VCC = 4V, ADC clock = 1 MHz VREF = VCC = 4V, ADC clock = 200 kHz Noise Reduction Mode VREF = VCC = 4V, ADC clock = 1 MHz Noise Reduction Mode Integral Non-Linearity (INL) (Accuracy after Offset and Gain Calibration) Differential Non-linearity (DNL) Gain Error Offset Error Conversion Time Clock Frequency VREF = VCC = 4V, ADC clock = 200 kHz VREF = VCC = 4V, ADC clock = 200 kHz VREF = VCC = 4V, ADC clock = 200 kHz VREF = VCC = 4V, ADC clock = 200 kHz Free Running Conversion 13 50 GND 38.5 100 0 1023 2 3 Condition Min Typ Max 10 Units Bits LSB LSB
Table 21-8.
Symbol
1.5
LSB
2.5
LSB
1
LSB
0.5 2.5 1.5 260 1000 VREF
LSB LSB LSB s kHz V kHz M LSB
VIN RAIN
Input Voltage Input Bandwidth Analog Input Resistance ADC Conversion Output
169
8263A-AVR-08/10
21.8
Serial Programming Characteristics
Figure 21-3. Serial Programming Timing
Rec eive Mode Transmit Mode
TPID ATA
t IVCH
t CHIX
t CLO V
TPIC LK
t CLC H
t CHCL
t CLCL
Table 21-9.
Symbol 1/tCLCL tCLCL tCLCH tCHCH tIVCH tCHIX tCLOV
Serial Programming Characteristics, TA = -40C to +85C, VCC = 5V 5%
Parameter Clock Frequency Clock Period Clock Low Pulse Width Clock High Pulse Width Data Input to Clock High Setup Time Data Input Hold Time After Clock High Data Output Valid After Clock Low Time 500 200 200 50 100 200 Min Typ Max 2 Units MHz ns ns ns ns ns ns
170
ATtiny40
8263A-AVR-08/10
ATtiny40
22. Typical Characteristics
The data contained in this section is largely based on simulations and characterization of similar devices in the same process and design methods. Thus, the data should be treated as indications of how the part will behave. The following charts show typical behavior. These figures are not tested during manufacturing. During characterisation devices are operated at frequencies higher than test limits but they are not guaranteed to function properly at frequencies higher than the ordering code indicates. All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled. Current consumption is a function of several factors such as operating voltage, operating frequency, loading of I/O pins, switching rate of I/O pins, code executed and ambient temperature. The dominating factors are operating voltage and frequency. A sine wave generator with rail-to-rail output is used as clock source but current consumption in Power-down mode is independent of clock selection. The difference between current consumption in Power-down mode with Watchdog Timer enabled and Power-down mode with Watchdog Timer disabled represents the differential current drawn by the Watchdog Timer. The current drawn from pins with a capacitive load may be estimated (for one pin) as follows:
I CP V CC x C L x f SW
where VCC = operating voltage, CL = load capacitance and fSW = average switching frequency of pin.
22.1
Supply Current of I/O Modules
The tables and formulas below can be used to calculate the additional current consumption for the different I/O modules in Active and Idle mode. The enabling or disabling of the I/O modules is controlled by the Power Reduction Register. See "Power Reduction Register" on page 28 for details. Table 22-1.
PRR bit VCC = 2V, f = 1MHz PRTIM0 PRTIM1 PRADC PRSPI PRTWI 4 A 5 A 190 A 3 A 5 A
Additional Current Consumption for different I/O modules (absolute values)
Typical numbers VCC = 3V, f = 4MHz 25 A 35 A 260 A 15 A 35 A VCC = 5V, f = 8MHz 110 A 150 A 470 A 75 A 160 A
171
8263A-AVR-08/10
Table 22-2 below can be used for calculating typical current consumption for other supply voltages and frequencies than those mentioned in the Table 22-1 above. Table 22-2. Additional Current Consumption (percentage) in Active and Idle mode
Current consumption additional to active mode with external clock (see Table 22-1 and Table 22-2) 2% 3% See Figure 22-16 on page 180 2% 4% Current consumption additional to idle mode with external clock (see Table 22-7 and Table 22-8) 15 % 20 % See Figure 22-16 on page 180 10 % 20 %
PRR bit PRTIM0 PRTIM1 PRADC PRSPI PRTWI
22.2
Current Consumption in Active Mode
Figure 22-1. Active Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
0,9
0,8
5.5 V
0,7
5.0 V
0,6
4.5 V
ICC [mA]
0,5
4.0 V
0,4
3.3 V
0,3
2.7 V
0,2
1.8 V
0,1
0 0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency [MHz]
172
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-2. Active Supply Current vs. Frequency (1 - 12 MHz)
6
5.5 V
5
5.0 V 4.5 V
4
ICC [mA]
4.0 V
3
3.3 V
2
2.7 V
1
1.8 V
0 0 2 4 6 8 10 12
Frequency [MHz]
Figure 22-3. Active Supply Current vs. VCC (Internal Oscillator, 8 MHz)
4,5
4
85 C 25 C -40 C
3,5
3
ICC [mA]
2,5
2
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
173
8263A-AVR-08/10
Figure 22-4. Active Supply Current vs. VCC (Internal Oscillator, 1 MHz)
1
0,9
85 C 25 C -40 C
0,8
0,7
0,6
ICC [mA]
0,5
0,4
0,3
0,2
0,1
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-5. Active Supply Current vs. VCC (Internal Oscillator, 128 kHz)
0,12
0,1
-40 C 25 C 85 C
0,08
ICC [mA]
0,06
0,04
0,02
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
174
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-6. Active Supply Current vs. VCC (Internal Oscillator, 32kHz)
0,045
0,04
0,035
-40 C 25 C 85 C
0,03
ICC [mA]
0,025
0,02
0,015
0,01
0,005
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
22.3
Current Consumption in Idle Mode
Figure 22-7. Idle Supply Current vs. Low Frequency (0.1 - 1.0 MHz)
0,12
5.5 V
0,1
5.0 V 4.5 V 4.0 V
0,06
0,08
ICC [mA]
3.3 V
0,04
2.7 V
0,02
1.8 V
0 0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
Frequency [MHz]
175
8263A-AVR-08/10
Figure 22-8. Idle Supply Current vs. Frequency (1 - 12 MHz)
1,4
5.5 V
1,2
5.0 V
1
4.5 V
0,8
ICC [mA]
4.0 V
0,6
0,4
3.3 V
2.7 V
0,2
1.8 V
0 0 2 4 6 8 10 12
Frequency [MHz]
Figure 22-9. Idle Supply Current vs. VCC (Internal Oscillator, 8 MHz)
1
0,9
85 C 25 C -40 C
0,8
0,7
0,6
ICC [mA]
0,5
0,4
0,3
0,2
0,1
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
176
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-10. Idle Supply Current vs. VCC (Internal Oscillator, 1 MHz)
0,3
0,25
-40 C 25 C 85 C
0,2
ICC [mA]
0,15
0,1
0,05
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-11. Idle Supply Current vs. VCC (Internal Oscillator, 128 kHz)
0,03
-40 C 25 C 85 C
0,025
0,02
ICC [mA]
0,015
0,01
0,005
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
177
8263A-AVR-08/10
Figure 22-12. Idle Supply Current vs. VCC (Internal Oscillator, 32kHz)
0,025
0,02
-40 C 25 C 85 C
0,015
ICC [mA]
0,01 0,005 0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
22.4
Current Consumption in Power-down Mode
Figure 22-13. Power-down Supply Current vs. VCC (Watchdog Timer Disabled)
0,8
0,7
85 C
0,6
0,5
ICC [uA]
0,4
0,3
0,2
0,1
25 C -40 C
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
178
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-14. Power-down Supply Current vs. VCC (Watchdog Timer Enabled)
12
-40 C
10
25 C 85 C
8
ICC [uA]
6
4
2
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
22.5
Current Consumption in Reset
Figure 22-15. Reset Supply Current vs. VCC (excluding Current Through the Reset Pull-up and No Clock
4,5
4
3,5
3
ICC [mA]
2,5
2
1,5
85 C -40 C 25 C
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
179
8263A-AVR-08/10
22.6
Current Consumption of Peripheral Units
Figure 22-16. ADC Current vs. VCC
400
350
300
250
ICC [uA]
200
150
100
50
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-17. Analog Comparator Current vs. VCC (Frequency 1 MHz)
140
120
100
80
ICC [uA]
60 40 20 0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
180
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-18. Watchdog Timer Current vs. VCC
12
10
-40 C 25 C 85 C
8
ICC [uA]
6
4
2
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-19. Brownout Detector Current vs. VCC
30
25
85 C 25 C -40 C
20
ICC [uA]
15
10
5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
181
8263A-AVR-08/10
22.7
Pull-up Resistors
Figure 22-20. I/O pin Pull-up Resistor Current vs. Input Voltage (VCC = 1.8V)
50
45
40
35
30
IOP [uA]
25
20
15
10
5
0 0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
25 C 85 C -40 C
VOP [V]
Figure 22-21. I/O Pin Pull-up Resistor Current vs. input Voltage (VCC = 2.7V)
80
70
60
50
IOP [uA]
40
30
20
10
0 0 0,5 1 1,5 2 2,5 3
25 C 85 C -40 C
VOP [V]
182
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-22. I/O pin Pull-up Resistor Current vs. Input Voltage (VCC = 5V)
160
140
120
100
IOP [uA]
80
60
40
20
0 0 1 2 3 4 5 6
25 C 85 C -40 C
VOP [V]
Figure 22-23. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 1.8V)
40
35
30
25
IRESET [uA]
20
15
10
5
0 0 0,2 0,4 0,6 0,8 1 1,2 1,4 1,6 1,8 2
25 C -40 C 85 C
VRESET [V]
183
8263A-AVR-08/10
Figure 22-24. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 2.7V)
60
50
40
IRESET [uA]
30
20
10
0 0 0,5 1 1,5 2 2,5 3
25 C -40 C 85 C
VRESET [V]
Figure 22-25. Reset Pull-up Resistor Current vs. Reset Pin Voltage (VCC = 5V)
120
100
80
IRESET [uA]
60
40
20
0 0 1 2 3 4 5 6
25 C -40 C 85 C
VRESET [V]
184
ATtiny40
8263A-AVR-08/10
ATtiny40
22.8 Output Driver Strength
Figure 22-26. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 1.8V)
0,8
0,7
85 C
0,6
0,5
25 C
VOL [V]
0,4
-40 C
0,3
0,2
0,1
0 0 1 2 3 4 5
IOL [mA]
Figure 22-27. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 3V)
0,8
0,7
0,6
85 C
0,5
25 C
VOL [V]
0,4
-40 C
0,3
0,2
0,1
0 0 1 2 3 4 5 6 7 8 9 10
IOL [mA]
185
8263A-AVR-08/10
Figure 22-28. VOL: Output Voltage vs. Sink Current (I/O Pin, VCC = 5V)
1
85 C
0,8
25 C
0,6
-40 C
VOL [V]
0,4 0,2 0 0 2 4 6 8 10 12 14 16 18 20
IOL [mA]
Figure 22-29. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 1.8V)
2
1,8
1,6
1,4
1,2
-40 C 25 C
VOH [V]
1
85 C
0,8
0,6
0,4
0,2
0 0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOH [mA]
186
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-30. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 3V)
3,5
3
2,5
-40 C 25 C 85 C
2
VOH [V]
1,5 1 0,5 0 0 1 2 3 4 5 6 7 8 9 10
IOH [mA]
Figure 22-31. VOH: Output Voltage vs. Source Current (I/O Pin, VCC = 5V)
5,1
5
4,9
4,8
4,7
VOH [V]
4,6
4,5
4,4
-40 C
4,3
25 C
4,2
85 C
4,1 0 2 4 6 8 10 12 14 16 18 20
IOH [mA]
187
8263A-AVR-08/10
Figure 22-32. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 1.8V)
1
0,8
0,6
VOL [V]
0,4
85 C 25 C
0,2
-40 C
0 0 0,1 0,2 0,3 0,4 0,5 0,6
IOL [mA]
Figure 22-33. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 3V)
2
1,8
1,6
1,4
1,2
VOL [V]
85 C
1
0,8
25 C -40 C
0,6
0,4
0,2
0 0 0,5 1 1,5 2 2,5 3
IOL [mA]
188
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-34. VOL: Output Voltage vs. Sink Current (Reset Pin as I/O, VCC = 5V)
2
1,8
1,6
1,4
1,2
VOL [V]
1
85 C 25 C -40 C
0,8
0,6
0,4
0,2
0 0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
IOL [mA]
Figure 22-35. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 1.8V
1,6
1,4
1,2
1
VOH [V]
0,8
0,6
0,4
85 C 25 C -40 C
0,2
0 0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
IOH [mA]
189
8263A-AVR-08/10
Figure 22-36. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 3V
3
2,5
2
VOH [V]
1,5
85 C 25 C -40 C
1
0,5
0 0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
IOH [mA]
Figure 22-37. VOH: Output Voltage vs. Source Current (Reset Pin as I/O, VCC = 5V
4,5
4
3,5
3
85 C 25 C -40 C
VOH [V]
2,5
2
1,5
1
0,5
0 0 0,1 0,2 0,3 0,4 0,5 0,6 0,7 0,8 0,9 1
IOH [mA]
190
ATtiny40
8263A-AVR-08/10
ATtiny40
22.9 Input Thresholds and Hysteresis
Figure 22-38. VIH: Input Threshold Voltage vs. VCC (I/O Pin, Read as `1')
3
85 C 25 C -40 C
2,5
2
Threshold [V]
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-39. VIL: Input Threshold Voltage vs. VCC (I/O Pin, Read as `0')
2,5
85 C 25 C -40 C
2
Threshold [V]
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
191
8263A-AVR-08/10
Figure 22-40. VIH-VIL: Input Hysteresis vs. VCC (I/O Pin)
0,6
-40 C
0,5
25 C
0,4
Hysteresis [V]
85 C
0,3
0,2
0,1
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-41. VIH: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as `1')
3,5
3
-40 C 25 C 85 C
2,5
Threshold [V]
2
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
192
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-42. VIL: Input Threshold Voltage vs. VCC (Reset Pin as I/O, Read as `0')
2,5
2
85 C 25 C -40 C
Threshold [V]
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-43. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin as I/O)
0,8
-40 C
0,7
0,6
25 C
0,5
Hysteresis [V]
85 C
0,4
0,3
0,2
0,1
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
193
8263A-AVR-08/10
22.10 BOD, Bandgap and Reset
Figure 22-44. BOD Threshold vs Temperature (BODLEVEL is 4.3V)
4,34
VCC RISING
4,32
4,3
4,28
Threshold [V]
4,26
VCC FALLING
4,24
4,22
4,2
4,18
4,16 -40 -20 0 20 40 60 80 100
Temperature [C]
Figure 22-45. BOD Threshold vs Temperature (BODLEVEL is 2.7V)
2,76
2,74
VCC RISING
2,72
Threshold [V]
2,7
2,68
VCC FALLING
2,66
2,64
2,62 -40 -20 0 20 40 60 80 100
Temperature [C]
194
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-46. BOD Threshold vs Temperature (BODLEVEL is 1.8V)
1,83
1,82
VCC RISING
1,81
1,8
Threshold [V]
VCC FALLING
1,79
1,78
1,77
1,76
1,75 -40 -20 0 20 40 60 80 100
Temperature [C]
Figure 22-47. Bandgap Voltage vs. Supply Voltage
1,09
1,085
1,08
1,075
85 C
Bandgap [V]
1,07
1,065
25 C
1,06
1,055
1,05
-40 C
1,045 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
195
8263A-AVR-08/10
Figure 22-48. VIH: Input Threshold Voltage vs. VCC (Reset Pin, Read as `1')
2,5
-40 C 25 C 85 C
2
Threshold [V]
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-49. VIL: Input Threshold Voltage vs. VCC (Reset Pin, Read as `0')
2,5
-40 C 25 C 85 C
2
Threshold [V]
1,5
1
0,5
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
196
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-50. VIH-VIL: Input Hysteresis vs. VCC (Reset Pin )
0,6
-40 C
0,5
0,4
Hysteresis [V]
25 C
0,3
0,2
85 C
0,1
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
Figure 22-51. Minimum Reset Pulse Width vs. VCC
2500
2000
Pulsewidth [ns]
1500
1000
500
85 C 25 C -40 C
0 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
197
8263A-AVR-08/10
22.11 Analog Comparator Offset
Figure 22-52. Analog Comparator Offset vs. Vin (VCC = 5V)
0 0 0,5 1 1,5 2 2,5 3 3,5 4 4,5 5
-0,002
-0,004
Offset [V]
-0,006
85 C
-0,008
25 C
-0,01
-0,012
-40 C
-0,014
Vin [V]
22.12 Internal Oscillator Speed
Figure 22-53. Watchdog Oscillator Frequency vs. VCC
0,109
0,108
0,107
0,106
-40 C
0,105
FRC [MHz]
0,104
25 C
0,103
0,102
0,101
0,1
85 C
0,099 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
198
ATtiny40
8263A-AVR-08/10
ATtiny40
Figure 22-54. Watchdog Oscillator Frequency vs. Temperature
0,109
0,108
0,107
0,106
0,105
FRC [MHz]
0,104
1.8 V
0,103
0,102
2.8 V 3.5 V 4.0 V 5.5 V
0,101
0,1
0,099 -40 -20 0 20 40 60 80 100
Temperature [C ]
Figure 22-55. Calibrated Oscillator Frequency vs. VCC
8,5
8,4
-40 C
8,3
25 C
8,2
FRC [MHz]
8,1
85 C
8
7,9
7,8
7,7 1,5 2 2,5 3 3,5 4 4,5 5 5,5
VCC [V]
199
8263A-AVR-08/10
Figure 22-56. Calibrated Oscillator Frequency vs. Temperature
8,3
8,2
8,1
FRC [MHz]
8
5.0 V
7,9
3.0 V
7,8
1.8 V
7,7 -40 -20 0 20 40 60 80 100
Temperature [C ]
Figure 22-57. Calibrated Oscillator Frequency vs, OSCCAL Value
16
14
-40 C 25 C 85 C
12
10
FRC [MHz]
8
6
4
2
0 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
OSCCAL [X1]
200
ATtiny40
8263A-AVR-08/10
ATtiny40
23. Register Summary
Address
0x3F 0x3E 0x3D 0x3C 0x3B 0x3A 0x39 0x38 0x37 0x36 0x35 0x34 0x33 0x32 0x31 0x30 0x2F 0x2E 0x2D 0x2C 0x2B 0x2A 0x29 0x28 0x27 0x26 0x25 0x24 0x23 0x22 0x21 0x20 0x1F 0x1E 0x1D 0x1C 0x1B 0x1A 0x19 0x18 0x17 0x16 0x15 0x14 0x13 0x12 0x11 0x10 0x0F 0x0E 0x0D 0x0C 0x0B 0x0A 0x09 0x08 0x07 0x06 0x05 0x04 0x03 0x02 0x01 0x00
Name
SREG SPH SPL CCP RSTFLR MCUCR OSCCAL Reserved CLKMSR CLKPSR PRR QTCSR NVMCMD NVMCSR WDTCSR SPCR SPSR SPDR TWSCRA TWSCRB TWSSRA TWSA TWSAM TWSD TCNT1H TIMSK TIFR TCCR1A TCNT1L OCR1A OCR1B RAMAR RAMDR PUEC PORTC DDRC PINC PCMSK2 TCCR0A TCCR0B TCNT0 OCR0A OCR0B ACSRA ACSRB ADCSRA ADCSRB ADMUX ADCH ADCL DIDR0 GIMSK GIFR PCMSK1 PCMSK0 PORTCR PUEB PORTB DDRB PINB PUEA PORTA DDRA PINA
Bit 7
I
Bit 6
T
Bit 5
H
Bit 4
S
Bit 3
V
Bit 2
N
Bit 1
Z
Bit 0
C
Page
Page 14 Page 13 Page 13 Page 13
Stack Pointer High Byte Stack Pointer Low Byte CPU Change Protection Register - ISC01 - ISC00 - - - BODS - - - - - NVMBSY WDIF SPIE SPIF TWSHE - TWDIF - - - - - WDIE SPE WCOL - - TWASIF - WDP3 DORD - TWDIE - TWCH - - MSTR - TWASIE - TWRA - - - - - - CLKPS3 - CLKPS2 CLKMS1 CLKPS1 PRTIM0 CLKMS0 CLKPS0 PRADC WDRF SM2 BORF SM1 EXTRF SM0 PORF SE
Page 39 Pages 30, 43 Page 25 Page 24 Page 24 Page 31 Page 144 Page 164
Oscillator Calibration Register
PRTWI PRSPI PRTIM1 QTouch Control and Status Register NVM Command Register - WDE CPOL - TWEN - TWC - WDP2 CPHA - TWSIE TWAA TWBE
- WDP1 SPR1 - TWPME TWDIR
- WDP0 SPR0 SPI2X TWSME TWAS
Page 164 Page 37 Page 128 Page 130 Page 130 Page 139 Page 140 Page 141 Page 142 Page 143 Page 143 Page 95
SPI Data Register TWCMD[1.0]
TWI Slave Address Register TWI Slave Address Mask Register TWI Slave Data Register Timer/Counter1 - Counter Register High Byte ICIE1 ICF1 TCW1 - - ICEN1 OCIE1B OCF1B ICNC1 OCIE1A OCF1A ICES1 TOIE1 TOV1 CTC1 OCIE0B OCF0B CS12 OCIE0A OCF0A CS11 TOIE0 TOV0 CS10
Pages 81, 96 Pages 81, 97 Page 94 Page 95 Page 95 Page 96 Page 19 Page 19
Timer/Counter1 - Counter Register Low Byte Timer/Counter1 - Compare Register A Timer/Counter1 - Compare Register B RAM Address Register RAM Data Register - - - - - COM0A1 FOC0A - - - - - COM0A0 FOC0B PUEC5 PORTC5 DDRC5 PINC5 PCINT17 COM0B1 TSM PUEC4 PORTC4 DDRC4 PINC4 PCINT16 COM0B0 PSR PUEC3 PORTC3 DDRC3 PINC3 PCINT15 - WGM02 PUEC2 PORTC2 DDRC2 PINC2 PCINT14 - CS02 PUEC1 PORTC1 DDRC1 PINC1 PCINT13 WGM01 CS01 PUEC0 PORTC0 DDRC0 PINC0 PCINT12 WGM00 CS00
Page 64 Page 64 Page 64 Page 64 Page 45 Page 76 Pages 79, 100 Page 80 Page 80 Page 81
Timer/Counter0 - Counter Register Timer/Counter0 - Compare Register A Timer/Counter0 - Compare Register B ACD HSEL ADEN VDEN -
ACBG/ACIRE
ACO ACLP ADATE - REFEN
ACI - ADIF - ADC0EN
ACIE ACCE ADIE ADLAR MUX3
ACIC ACME ADPS2 ADTS2 MUX2
ACIS1 ACIRS1 ADPS1 ADTS1 MUX1
ACIS0 ACIRS0 ADPS0 ADTS0 MUX0
Page 102 Page 103 Page 119 Page 120 Page 117 Page 118 Page 118
HLEV ADSC VDPD REFS
ADC Conversion Result - High Byte ADC Conversion Result - Low Byte ADC7D - - - PCINT7 ADC11D - - - - PUEA7 PORTA7 DDRA7 PINA7 ADC6D PCIE2 PCIF2 - PCINT6 ADC10D - - - - PUEA6 PORTA6 DDRA6 PINA6 ADC5D PCIE1 PCIF1 - PCINT5 ADC9D - - - - PUEA5 PORTA5 DDRA5 PINA5 ADC4D PCIE0 PCIF0 - PCINT4 ADC8D - - - - PUEA4 PORTA4 DDRA4 PINA4 ADC3D - - PCINT11 PCINT3 - PUEB3 PORTB3 DDRB3 PINB3 PUEA3 PORTA3 DDRA3 PINA3 ADC2D - - PCINT10 PCINT2 BBMC PUEB2 PORTB2 DDRB2 PINB2 PUEA2 PORTA2 DDRA2 PINA2 ADC1D - - PCINT9 PCINT1 BBMB PUEB1 PORTB1 DDRB1 PINB1 PUEA1 PORTA1 DDRA1 PINA1 ADC0D INT0 INTF0 PCINT8 PCINT0 BBMA PUEB0 PORTB0 DDRB0 PINB0 PUEA0 PORTA0 DDRA0 PINA0
Pages 104, 121 Page 43 Page 44 Page 45 Page 45 Pages 62, 121 Page 63 Page 63 Page 63 Page 64 Page 63 Page 63 Page 63 Page 63
201
8263A-AVR-08/10
Note:
1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. 2. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. 3. Some of the Status Flags are cleared by writing a logical one to them. Note that, unlike most other AVRs, the CBI and SBI instructions will only operation the specified bit, and can therefore be used on registers containing such Status Flags. The CBI and SBI instructions work with registers 0x00 to 0x1F only.
202
ATtiny40
8263A-AVR-08/10
ATtiny40
24. Instruction Set Summary
Mnemonics
ADD ADC SUB SUBI SBC SBCI AND ANDI OR ORI EOR COM NEG SBR CBR INC DEC TST CLR SER RJMP IJMP RCALL ICALL RET RETI CPSE CP CPC CPI SBRC SBRS SBIC SBIS BRBS BRBC BREQ BRNE BRCS BRCC BRSH BRLO BRMI BRPL BRGE BRLT BRHS BRHC BRTS BRTC BRVS BRVC BRIE BRID LSL LSR ROL ROR ASR SWAP BSET Rd,Rr Rd,Rr Rd,Rr Rd,K Rr, b Rr, b A, b A, b s, k s, k k k k k k k k k k k k k k k k k k k Rd Rd Rd Rd Rd Rd s k
Operands
Rd, Rr Rd, Rr Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd Rd Rd,K Rd,K Rd Rd Rd Rd Rd k Add without Carry Add with Carry Subtract without Carry Subtract Immediate Subtract with Carry
Description
Rd Rd + Rr
Operation
Flags
Z,C,N,V,S,H Z,C,N,V,S,H Z,C,N,V,S,H Z,C,N,V,S,H Z,C,N,V,S,H Z,C,N,V,S,H Z,N,V,S Z,N,V,S Z,N,V,S Z,N,V,S Z,N,V,S Z,C,N,V,S Z,C,N,V,S,H Z,N,V,S Z,N,V,S Z,N,V,S Z,N,V,S Z,N,V,S Z,N,V,S None None None None None None I None Z, C,N,V,S,H Z, C,N,V,S,H Z, C,N,V,S,H None None None None None None None None None None None None None None None None None None None None None None None None Z,C,N,V,H Z,C,N,V Z,C,N,V,H Z,C,N,V Z,C,N,V None SREG(s)
#Clocks
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 3/4 3/4 4/5 4/5 1/2/3 1 1 1 1/2/3 1/2/3 1/2/3 1/2/3 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1 1 1 1 1 1 1
ARITHMETIC AND LOGIC INSTRUCTIONS
Rd Rd + Rr + C Rd Rd - Rr Rd Rd - K Rd Rd - Rr - C Rd Rd - K - C Rd Rd * Rr Rd Rd * K Rd Rd v Rr Rd Rd v K Rd Rd Rr Rd $FF - Rd Rd $00 - Rd Rd Rd v K Rd Rd * ($FFh - K) Rd Rd + 1 Rd Rd - 1 Rd Rd * Rd Rd Rd Rd Rd $FF PC PC + k + 1 PC(15:0) Z, PC(21:16) 0 PC PC + k + 1 PC(15:0) Z, PC(21:16) 0 PC STACK PC STACK if (Rd = Rr) PC PC + 2 or 3 Rd - Rr Rd - Rr - C Rd - K if (Rr(b)=0) PC PC + 2 or 3 if (Rr(b)=1) PC PC + 2 or 3 if (I/O(A,b)=0) PC PC + 2 or 3 if (I/O(A,b)=1) PC PC + 2 or 3 if (SREG(s) = 1) then PCPC+k + 1 if (SREG(s) = 0) then PCPC+k + 1 if (Z = 1) then PC PC + k + 1 if (Z = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (N = 1) then PC PC + k + 1 if (N = 0) then PC PC + k + 1 if (N V= 0) then PC PC + k + 1 if (N V= 1) then PC PC + k + 1 if (H = 1) then PC PC + k + 1 if (H = 0) then PC PC + k + 1 if (T = 1) then PC PC + k + 1 if (T = 0) then PC PC + k + 1 if (V = 1) then PC PC + k + 1 if (V = 0) then PC PC + k + 1 if ( I = 1) then PC PC + k + 1 if ( I = 0) then PC PC + k + 1 Rd(n+1) Rd(n), Rd(0) 0 Rd(n) Rd(n+1), Rd(7) 0 Rd(0)C,Rd(n+1) Rd(n),CRd(7) Rd(7)C,Rd(n) Rd(n+1),CRd(0) Rd(n) Rd(n+1), n=0..6 Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) SREG(s) 1
Subtract Immediate with Carry Logical AND Logical AND with Immediate Logical OR Logical OR with Immediate Exclusive OR One's Complement Two's Complement Set Bit(s) in Register Clear Bit(s) in Register Increment Decrement Test for Zero or Minus Clear Register Set Register Relative Jump Indirect Jump to (Z) Relative Subroutine Call Indirect Call to (Z) Subroutine Return Interrupt Return Compare, Skip if Equal Compare Compare with Carry Compare with Immediate Skip if Bit in Register Cleared Skip if Bit in Register is Set Skip if Bit in I/O Register Cleared Skip if Bit in I/O Register is Set Branch if Status Flag Set Branch if Status Flag Cleared Branch if Equal Branch if Not Equal Branch if Carry Set Branch if Carry Cleared Branch if Same or Higher Branch if Lower Branch if Minus Branch if Plus Branch if Greater or Equal, Signed Branch if Less Than Zero, Signed Branch if Half Carry Flag Set Branch if Half Carry Flag Cleared Branch if T Flag Set Branch if T Flag Cleared Branch if Overflow Flag is Set Branch if Overflow Flag is Cleared Branch if Interrupt Enabled Branch if Interrupt Disabled Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Swap Nibbles Flag Set
BRANCH INSTRUCTIONS
BIT AND BIT-TEST INSTRUCTIONS
203
8263A-AVR-08/10
Mnemonics
BCLR SBI CBI BST BLD SEC CLC SEN CLN SEZ CLZ SEI CLI SES CLS SEV CLV SET CLT SEH CLH s
Operands
Flag Clear Set Bit in I/O Register Clear Bit in I/O Register A, b A, b Rr, b Rd, b
Description
SREG(s) 0 I/O(A, b) 1 I/O(A, b) 0 T Rr(b) Rd(b) T C1 C0 N1 N0 Z1 Z0 I1 I0 S1 S0 V1 V0 T1 T0 H1 H0 Rd Rr Rd K Rd (X)
Operation
Flags
SREG(s) None None T None C C N N Z Z I I S S V V T T H H None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None
#Clocks
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1/2 2 2/3 1/2 2 2/3 1/2 2 2/3 1 1 1 2 1 1 2 1 1 2 1 1 1 2 2 1 1 1 1
Bit Store from Register to T Bit load from T to Register Set Carry Clear Carry Set Negative Flag Clear Negative Flag Set Zero Flag Clear Zero Flag Global Interrupt Enable Global Interrupt Disable Set Signed Test Flag Clear Signed Test Flag Set Two's Complement Overflow. Clear Two's Complement Overflow Set T in SREG Clear T in SREG Set Half Carry Flag in SREG Clear Half Carry Flag in SREG
DATA TRANSFER INSTRUCTIONS
MOV LDI LD LD LD LD LD LD LD LD LD LDS ST ST ST ST ST ST ST ST ST STS IN OUT PUSH POP
Rd, Rr Rd, K Rd, X Rd, X+ Rd, - X Rd, Y Rd, Y+ Rd, - Y Rd, Z Rd, Z+ Rd, -Z Rd, k X, Rr X+, Rr - X, Rr Y, Rr Y+, Rr - Y, Rr Z, Rr Z+, Rr -Z, Rr k, Rr Rd, A A, Rr Rr Rd
Copy Register Load Immediate Load Indirect Load Indirect and Post-Increment Load Indirect and Pre-Decrement Load Indirect Load Indirect and Post-Increment Load Indirect and Pre-Decrement Load Indirect Load Indirect and Post-Increment Load Indirect and Pre-Decrement Store Direct from SRAM Store Indirect Store Indirect and Post-Increment Store Indirect and Pre-Decrement Store Indirect Store Indirect and Post-Increment Store Indirect and Pre-Decrement Store Indirect Store Indirect and Post-Increment. Store Indirect and Pre-Decrement Store Direct to SRAM In from I/O Location Out to I/O Location Push Register on Stack Pop Register from Stack Break No Operation Sleep Watchdog Reset
Rd (X), X X + 1 X X - 1, Rd (X) Rd (Y) Rd (Y), Y Y + 1 Y Y - 1, Rd (Y) Rd (Z) Rd (Z), Z Z+1 Z Z - 1, Rd (Z) Rd (k) (X) Rr (X) Rr, X X + 1 X X - 1, (X) Rr (Y) Rr (Y) Rr, Y Y + 1 Y Y - 1, (Y) Rr (Z) Rr (Z) Rr, Z Z + 1 Z Z - 1, (Z) Rr (k) Rr Rd I/O (A) I/O (A) Rr STACK Rr Rd STACK (see specific descr. for Break) (see specific descr. for Sleep) (see specific descr. for WDR)
MCU CONTROL INSTRUCTIONS BREAK
NOP SLEEP WDR
204
ATtiny40
8263A-AVR-08/10
ATtiny40
25. Ordering Information
Speed (MHz) Power Supply (V) Ordering Code(1) ATtiny40-SU ATtiny40-SUR ATtiny40-XU ATtiny40-XUR ATTINY40-MMH(3) ATTINY40-MMHR(3) Package(2) 20S2 20S2 20X 20X 20M2(3) 20M2(3) Operational Range
12
1.8 - 5.5
Industrial (-40C to +85C)(4)
Notes:
1. Code indicators: - H: NiPdAu lead finish - U: matte tin - R: tape & reel 2. All packages are Pb-free, halide-free and fully green and they comply with the European directive for Restriction of Hazardous Substances (RoHS). 3. Topside marking for ATtiny40: - 1st Line: T40 - 2nd Line: xx - 3rd Line: xxx 4. These devices can also be supplied in wafer form. Please contact your local Atmel sales office for detailed ordering information and minimum quantities.
Package Type 20S2 20X 20M2 20-lead, 0.300" Wide Body, Plastic Gull Wing Small Outline Package (SOIC) 20-lead, 4.4 mm Body, Plastic Thin Shrink Small Outline Package (TSSOP) 20-pad, 3 x 3 x 0.85 mm Body, Very Thin Quad Flat No Lead Package (VQFN)
205
8263A-AVR-08/10
26. Packaging Information
26.1 20S2
206
ATtiny40
8263A-AVR-08/10
ATtiny40
26.2 20X
Dimensions in Millimeters and (Inches). Controlling dimension: Millimeters. JEDEC Standard MO-153 AC
INDEX MARK
PIN 1
4.50 (0.177) 6.50 (0.256) 4.30 (0.169) 6.25 (0.246)
6.60 (.260) 6.40 (.252)
1.20 (0.047) MAX
0.65 (.0256) BSC 0.30 (0.012) 0.19 (0.007)
0.15 (0.006) 0.05 (0.002)
SEATING PLANE
0 ~ 8
0.20 (0.008) 0.09 (0.004)
0.75 (0.030) 0.45 (0.018)
10/23/03 2325 Orchard Parkway San Jose, CA 95131 TITLE 20X, (Formerly 20T), 20-lead, 4.4 mm Body Width, Plastic Thin Shrink Small Outline Package (TSSOP) DRAWING NO. 20X REV. C
R
207
8263A-AVR-08/10
26.3
20M2
D
C y
Pin 1 ID
E
SIDE VIEW
TOP VIEW A1 A D2
16 17 18 19 20 COMMON DIMENSIONS (Unit of Measure = mm) SYMBOL A 2 MIN 0.75 0.00 0.17 NOM 0.80 0.02 0.22 0.152 2.90 1.40 2.90 1.40 - 0.35 0.20 0.00 3.00 1.55 3.00 1.55 0.45 0.40 - - 3.10 1.70 3.10 1.70 - 0.45 - 0.08 MAX 0.85 0.05 0.27 NOTE
C0.18 (8X)
15 14
Pin #1 Chamfer (C 0.3)
1
e E2 13
12 11 3 4 5
A1 b C D D2 E
b
10 9 8 7 6
E2 e
L BOTTOM VIEW
K
0.3 Ref (4x)
L K y
10/24/08 Package Drawing Contact: packagedrawings@atmel.com GPC TITLE 20M2, 20-pad, 3 x 3 x 0.85 mm Body, Lead Pitch 0.45 mm, ZFC 1.55 x 1.55 mm Exposed Pad, Thermally Enhanced Plastic Very Thin Quad Flat No Lead Package (VQFN) DRAWING NO. 20M2 REV. B
208
ATtiny40
8263A-AVR-08/10
ATtiny40
27. Errata
The revision letters in this section refer to the revision of the corresponding ATtiny40 device.
27.1 27.2
Rev. B
No known errata.
Rev. A
Not sampled.
209
8263A-AVR-08/10
28. Datasheet Revision History
28.1 Rev. 8263A - 08/10
1. Initial revision. Copied and modified from 8235_t20.
210
ATtiny40
8263A-AVR-08/10
ATtiny40
Table of Contents
Features ..................................................................................................... 1 1 2 3 Pin Configurations ................................................................................... 2
1.1 Pin Description ..................................................................................................2
Overview ................................................................................................... 4 General Information ................................................................................. 6
3.1 3.2 3.3 3.4 Resources .........................................................................................................6 Code Examples .................................................................................................6 Data Retention ...................................................................................................6 Disclaimer ..........................................................................................................6
4
CPU Core .................................................................................................. 7
4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 Architectural Overview .......................................................................................7 ALU - Arithmetic Logic Unit ...............................................................................8 Status Register ..................................................................................................8 General Purpose Register File ..........................................................................9 Stack Pointer ...................................................................................................10 Instruction Execution Timing ...........................................................................10 Reset and Interrupt Handling ...........................................................................11 Register Description ........................................................................................13
5
Memories ................................................................................................ 15
5.1 5.2 5.3 5.4 In-System Re-programmable Flash Program Memory ....................................15 Data Memory ...................................................................................................15 I/O Memory ......................................................................................................18 Register Description ........................................................................................19
6
Clock System ......................................................................................... 20
6.1 6.2 6.3 6.4 6.5 Clock Subsystems ...........................................................................................20 Clock Sources .................................................................................................21 System Clock Prescaler ..................................................................................22 Starting ............................................................................................................22 Register Description ........................................................................................24
7
Power Management and Sleep Modes ................................................. 27
7.1 7.2 Sleep Modes ....................................................................................................27 Software BOD Disable .....................................................................................28
i
8263A-AVR-08/10
7.3 7.4 7.5
Power Reduction Register ...............................................................................28 Minimizing Power Consumption ......................................................................29 Register Description ........................................................................................30
8
System Control and Reset .................................................................... 32
8.1 8.2 8.3 8.4 8.5 Resetting the AVR ...........................................................................................32 Reset Sources .................................................................................................32 Internal Voltage Reference ..............................................................................35 Watchdog Timer ..............................................................................................35 Register Description ........................................................................................37
9
Interrupts ................................................................................................ 40
9.1 9.2 9.3 Interrupt Vectors ..............................................................................................40 External Interrupts ...........................................................................................41 Register Description ........................................................................................43
10 I/O Ports .................................................................................................. 46
10.1 10.2 10.3 10.4 Overview ..........................................................................................................46 Ports as General Digital I/O .............................................................................47 Alternate Port Functions ..................................................................................52 Register Description ........................................................................................62
11 Timer/Counter0 ...................................................................................... 65
11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 Features ..........................................................................................................65 Overview ..........................................................................................................65 Clock Sources .................................................................................................66 Counter Unit ....................................................................................................66 Output Compare Unit .......................................................................................67 Compare Match Output Unit ............................................................................69 Modes of Operation .........................................................................................70 Timer/Counter Timing Diagrams .....................................................................74 Register Description ........................................................................................76
12 Timer/Counter1 ...................................................................................... 83
12.1 12.2 12.3 12.4 12.5 Features ..........................................................................................................83 Overview ..........................................................................................................83 Clock Sources .................................................................................................84 Counter Unit ....................................................................................................84 Input Capture Unit ...........................................................................................85
ii
ATtiny40
8263A-AVR-08/10
ATtiny40
12.6 12.7 12.8 12.9 12.10 Output Compare Unit .......................................................................................87 Modes of Operation .........................................................................................87 Timer/Counter Timing Diagrams .....................................................................89 Accessing Registers in 16-bit Mode ................................................................90 Register Description ........................................................................................94
13 Timer/Counter Prescaler ....................................................................... 98
13.1 13.2 13.3 Prescaler Reset ...............................................................................................98 External Clock Source .....................................................................................98 Register Description ......................................................................................100
14 Analog Comparator ............................................................................. 101
14.1 14.2 Analog Comparator Multiplexed Input ...........................................................102 Register Description ......................................................................................102
15 Analog to Digital Converter ................................................................ 105
15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 15.13 Features ........................................................................................................105 Overview ........................................................................................................105 Operation .......................................................................................................106 Starting a Conversion ....................................................................................107 Prescaling and Conversion Timing ................................................................108 Changing Channel or Reference Selection ...................................................111 ADC Noise Canceler .....................................................................................112 Analog Input Circuitry ....................................................................................112 Noise Canceling Techniques .........................................................................113 ADC Accuracy Definitions .............................................................................113 ADC Conversion Result .................................................................................116 Temperature Measurement ...........................................................................116 Register Description ......................................................................................117
16 SPI - Serial Peripheral Interface ......................................................... 122
16.1 16.2 16.3 16.4 16.5 Features ........................................................................................................122 Overview ........................................................................................................122 SS Pin Functionality ......................................................................................126 Data Modes ...................................................................................................127 Register Description ......................................................................................128
17 TWI - Two Wire Slave Interface .......................................................... 131
17.1 Features ........................................................................................................131
iii
8263A-AVR-08/10
17.2 17.3 17.4 17.5
Overview ........................................................................................................131 General TWI Bus Concepts ...........................................................................131 TWI Slave Operation .....................................................................................137 Register Description ......................................................................................139
18 Touch Sensing ..................................................................................... 144 19 Programming Interface ........................................................................ 145
19.1 19.2 19.3 19.4 19.5 19.6 19.7 Features ........................................................................................................145 Overview ........................................................................................................145 Physical Layer of Tiny Programming Interface ..............................................145 Access Layer of Tiny Programming Interface ................................................149 Instruction Set ................................................................................................150 Accessing the Non-Volatile Memory Controller .............................................153 Control and Status Space Register Descriptions ..........................................153
20 Memory Programming ......................................................................... 156
20.1 20.2 20.3 20.4 20.5 20.6 20.7 Features ........................................................................................................156 Overview ........................................................................................................156 Non-Volatile Memories ..................................................................................157 Accessing the NVM .......................................................................................160 Self programming ..........................................................................................163 External Programming ...................................................................................163 Register Description ......................................................................................164
21 Electrical Characteristics .................................................................... 165
21.1 21.2 21.3 21.4 21.5 21.6 21.7 21.8 Absolute Maximum Ratings* .........................................................................165 DC Characteristics .........................................................................................165 Speed ............................................................................................................166 Clock Characteristics .....................................................................................167 System and Reset Characteristics ................................................................168 Analog Comparator Characteristics ...............................................................169 ADC Characteristics ......................................................................................169 Serial Programming Characteristics ..............................................................170
22 Typical Characteristics ........................................................................ 171
22.1 22.2 22.3 Supply Current of I/O Modules ......................................................................171 Current Consumption in Active Mode ............................................................172 Current Consumption in Idle Mode ................................................................175
iv
ATtiny40
8263A-AVR-08/10
ATtiny40
22.4 22.5 22.6 22.7 22.8 22.9 22.10 22.11 22.12 Current Consumption in Power-down Mode ..................................................178 Current Consumption in Reset ......................................................................179 Current Consumption of Peripheral Units ......................................................180 Pull-up Resistors ...........................................................................................182 Output Driver Strength ...................................................................................185 Input Thresholds and Hysteresis ...................................................................191 BOD, Bandgap and Reset .............................................................................194 Analog Comparator Offset .............................................................................198 Internal Oscillator Speed ...............................................................................198
23 Register Summary ............................................................................... 201 24 Instruction Set Summary .................................................................... 203 25 Ordering Information ........................................................................... 205 26 Packaging Information ........................................................................ 206
26.1 26.2 26.3 20S2 ..............................................................................................................206 20X ................................................................................................................207 20M2 ..............................................................................................................208
27 Errata ..................................................................................................... 209
27.1 27.2 Rev. B ............................................................................................................209 Rev. A ............................................................................................................209
28 Datasheet Revision History ................................................................ 210
28.1 Rev. 8263A - 08/10 .......................................................................................210
Table of Contents....................................................................................... i
v
8263A-AVR-08/10
Headquarters
Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600
International
Atmel Asia Unit 1-5 & 16, 19/F BEA Tower, Millennium City 5 418 Kwun Tong Road Kwun Tong, Kowloon Hong Kong Tel: (852) 2245-6100 Fax: (852) 2722-1369 Atmel Europe Le Krebs 8, Rue Jean-Pierre Timbaud BP 309 78054 Saint-Quentin-enYvelines Cedex France Tel: (33) 1-30-60-70-00 Fax: (33) 1-30-60-71-11 Atmel Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581
Product Contact
Web Site www.atmel.com Technical Support avr@atmel.com Sales Contact www.atmel.com/contacts
Literature Requests www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL'S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL'S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel's products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
(c) 2010 Atmel Corporation. All rights reserved. Atmel(R), logo and combinations thereof, AVR (R) and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
8263A-AVR-08/10


▲Up To Search▲   

 
Price & Availability of ATTINY40-MMH

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X